Search code examples
mysqlbitbit-fields

get one bit by index from bit field, mysql


Is there a way to get one bit (or bool) from a bit field in mysql?

The only solution i've came up with is to use the following: i want the bit value at position three.

SELECT bit_count(bin(column) & b'100') AS bitValue FROM table;

The output from this query is either a one or a zero. But it does not look so nice. Is there a better way to get the bit value at a specific position in a bit field? Reading the bit values would be done heavily at my web application, do you think that the way of getting the value that i used above would be a problem for the performance?? i mean with both a bit_count and a BIN() and "and" operator..

I am looking for something like:

SELECT column(3) FROM table;

Thanks for reading!

Mattias.


Solution

  • If you are worried about read performance and the bit you are interested in is fixed, try to extract the bit and insert it into a boolean column. If the bit you are trying to extract is dynamic, I think your solutions is optimal.