Example 1
Find users who have the WRITE permission bit set
The WRITE flag has value 2 (binary 10). Testing permissions & 2 = 2 isolates bit position 1. Alice has permissions 3 (binary 011 = READ + WRITE): 3 & 2 = 2 ✔. Bob has permissions 5 (binary 101 = READ + DELETE): 5 & 2 = 0 ✘ — bit 1 is not set. Carol has permissions 7 (binary 111 = READ + WRITE + DELETE): 7 & 2 = 2 ✔. Dave has 0: all bits clear. To grant WRITE to bob: UPDATE users SET permissions = permissions | 2 WHERE username = 'bob'. To revoke DELETE (4) from carol: UPDATE users SET permissions = permissions & ~4 WHERE username = 'carol'. To check whether a user has all of READ (1) and WRITE (2), test permissions & 3 = 3 — any value where both bits are set satisfies this.
CREATE TABLE users (username VARCHAR(20), permissions INT);
INSERT INTO
users
VALUES
('alice', 3),
('bob', 5),
('carol', 7),
('dave', 0);SELECT username, permissions FROM users WHERE permissions & 2 = 2 ORDER BY username;| username | permissions |
|---|---|
| alice | 3 |
| carol | 7 |
Output is identical across all supported engines.