Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Bitwise Masking

I have a table that store access privileges as a bitwise mask:

  • 0 none
  • 1 user
  • 2 super-user

I want to query, for instance, all accounts that have user + super-user priviledges, I thought that:

SELECT * FROM "accounts" WHERE "privileges" & 3;

Would work, but it's also returning all normal user (1) accounts. I can see that this it's correct because:

  1    (01)
& 3    (11)
-----------
= 1    (01)

I remember that this was easily doable in MySQL for instance, but I forgot how in the meantime.

I think the solution is probably a simple one, can anyone give me a hint on this?

like image 668
Alix Axel Avatar asked Sep 07 '13 03:09

Alix Axel


1 Answers

Check whether the result of "privileges" & 3 is actually equal to 3:

SELECT * FROM "accounts" WHERE ("privileges" & 3) == 3;

Otherwise, the query will select records where at least one bit is set.

like image 171
Michael Liu Avatar answered Oct 22 '22 02:10

Michael Liu