BIT_AND BIT_OR Flag Mask Rollups
Roll up integer permission masks per team with BIT_OR as the union of grants and BIT_AND as what every member shares, then test single bits with an & mask.
Code
CREATE TABLE members (
team_id int NOT NULL,
member text NOT NULL,
-- flag mask:read=1, write=2, admin=4
perms int NOT NULL
);
INSERT INTO members VALUES
(1, 'ada', 3), -- read | write
(1, 'raj', 1), -- read
(1, 'kim', 7), -- read | write | admin
(2, 'lin', 2), -- write
(2, 'joe', 6); -- write | admin
-- rollups:BIT_OR = 组内任一成员具备的权限并集;
-- BIT_AND = 全员共有的权限交集
SELECT team_id,
BIT_OR(perms) AS union_perms,
BIT_AND(perms) AS shared_perms,
(BIT_OR(perms) & 4) > 0 AS any_admin
FROM members
GROUP BY team_id
ORDER BY team_id;What the code does
The file runs SELECT / INSERT / CREATE statements, touching members.
Mechanically, the statements are built from: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Applying it
The members table is the working surface here.
Statements that matter
SELECT team_id,
BIT_OR(perms) AS union_perms,
BIT_AND(perms) AS shared_perms,
(BIT_OR(perms) & 4) > 0 AS any_admin
FROM members
GROUP BY team_id
ORDER BY team_id;
INSERT INTO members VALUES
(1, 'ada', 3), -- read | write
(1, 'raj', 1), -- read
(1, 'kim', 7), -- read | write | admin
(2, 'lin', 2), -- write
(2, 'joe', 6); -- write | admin
CREATE TABLE members (
team_id int NOT NULL,
member text NOT NULL,
perms int NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `members` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.