Column Level Grant Privileges
GRANT SELECT on a column list keeps sensitive columns out of a role's reach, and has_column_privilege reports per-column access before queries run.
Code
-- column-level GRANT (privileges):列级授权只放行非敏感列,敏感列对分析角色不可见
CREATE ROLE analyst NOLOGIN;
CREATE TABLE employees (
id int PRIMARY KEY,
name text NOT NULL,
salary_cents bigint NOT NULL
);
INSERT INTO employees VALUES (1, 'ada', 210000), (2, 'grace', 185000);
-- 只授权两列:SELECT salary_cents 在该角色下会报权限错误
GRANT SELECT (id, name) ON employees TO analyst;
SET ROLE analyst;
SELECT id, name FROM employees ORDER BY id;
RESET ROLE;
-- 上线前逐列探测:敏感列 false,可见列 true
SELECT has_column_privilege('analyst', 'employees', 'salary_cents', 'SELECT') AS salary_readable,
has_column_privilege('analyst', 'employees', 'name', 'SELECT') AS name_readable;
REVOKE SELECT (id, name) ON employees FROM analyst;
DROP ROLE analyst;
DROP TABLE employees;How it works
What runs here is SELECT / INSERT / CREATE — employees and analyst are the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the employees table.
Statements that matter
SELECT has_column_privilege('analyst', 'employees', 'salary_cents', 'SELECT') AS salary_readable,
has_column_privilege('analyst', 'employees', 'name', 'SELECT') AS name_readable;
CREATE TABLE employees (
id int PRIMARY KEY,
name text NOT NULL,
salary_cents bigint NOT NULL
);
INSERT INTO employees VALUES (1, 'ada', 210000), (2, 'grace', 185000);
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.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Which tables does this file reference?
- `employees`, `analyst` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.