Sub topic 9
Table and Column Privileges
Assume you can connect to PostgreSQL, know basic SQL, and have an existing schema and roles. This chapter uses an orders table owned by app_owner, with app_readonly and app_writer as group roles.
A table privilege controls an action on rows in a table. PostgreSQL supports several table privileges:
| Privilege | Allows |
|---|---|
| SELECT | Read rows or selected columns |
| INSERT | Add rows |
| UPDATE | Change rows or selected columns |
| DELETE | Remove rows |
| TRUNCATE | Empty the table |
| REFERENCES | Create foreign keys that refer to the table |
A role may need more than one privilege. For example, an application that edits orders usually needs SELECT, INSERT, and UPDATE. It might not need DELETE.
Granting table privileges
The following commands grant access to an existing table. The role executing them must own the table or have suitable administrative authority.
GRANT USAGE ON SCHEMA shop TO app_readonly, app_writer;
GRANT SELECT
ON shop.orders
TO app_readonly;
GRANT SELECT, INSERT, UPDATE
ON shop.orders
TO app_writer;USAGE on the schema is required before a role can access objects through that schema. A table grant alone does not make shop.orders usable.
You can remove a privilege with REVOKE:
REVOKE UPDATE
ON shop.orders
FROM app_writer;A role can still receive the same privilege through another membership or through PUBLIC, the pseudo-role representing every role. Therefore, inspect the effective access after changing grants.
Restricting access to columns
A column privilege names the columns a role may read or change. This is useful when a table contains sensitive data.
GRANT SELECT (id, customer)
ON shop.orders
TO app_readonly;
GRANT UPDATE (customer)
ON shop.orders
TO app_writer;The first grant permits app_readonly to select only id and customer, provided the role does not also have table-level SELECT. The second permits updates to customer, but not to sales_rep or total.
Column restrictions apply to SELECT, INSERT, UPDATE, and REFERENCES. DELETE and TRUNCATE apply to the table as a whole.
A table-level grant is broader than a column-level grant. If app_readonly already has GRANT SELECT ON shop.orders, adding a column-level grant does not narrow that access. Revoke the table privilege first if you need a column-only policy.
REVOKE SELECT ON shop.orders FROM app_readonly;
GRANT SELECT (id, customer)
ON shop.orders
TO app_readonly;For INSERT, a role can be limited to specific columns. PostgreSQL then requires omitted columns to have defaults or accept NULL:
GRANT INSERT (customer, total)
ON shop.orders
TO app_writer;How PostgreSQL evaluates access
Exercise
app_writer has UPDATE on shop.orders but only column-level UPDATE on customer. Can it update total?
Show answer
No. It needs UPDATE on total, or a table-level UPDATE privilege, before it can change that column.