Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Integer Type - Detect bit

With SQL, I would like to detect if a certain bit is on with an integer column type (MySQL)?

How would I go about this?

Basically, I want to detect if a bit is on, if it is on, then ignore.

I am using something like this now:

WHERE (column & 2) != 2
like image 559
RoR Avatar asked Aug 23 '11 21:08

RoR


People also ask

How do I select a bit value in SQL?

You can use the CONVERT operator. CAST or CONVERT will work. Show activity on this post. 1 is the display for a true bit.

How bit data type is defined in SQL?

SQL Server bit data type is an integer data type that can take only one of these values: 0, 1, NULL. With regard to the storage, if there are less than 9 columns of the bit data in the table, they are stored as 1 byte. If there are 9 to 16 such columns, they consume 2 bytes and so on.

Is integer check in SQL?

Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.

How do I return a bit value in SQL Server?

We can use the CAST method to cast from one data type to another. You might want to cast a float value to int value for that we use CAST(). So in case three is based on the condition we are casting int 1 to BIT which returns True value and int 0 to BIT which returns False value.


1 Answers

Say you're checking for the 3rd bit then...

SELECT bits & 8 = 8 FROM table;

This returns a binary (1 or 0) for whether the bit in question (in this case the third) is on or off for each row in the column 'bits'.

using 2^x for the xth bit instead of 8.

for example, to check the 5th bit we would use 2^5 = 32

SELECT bits & 32 = 32 FROM table;

However, this is needlessly complicated. Simply use boolean values in several columns and it will make things much easier.

like image 197
PyKing Avatar answered Nov 10 '22 00:11

PyKing