Sub topic 5
One policy per command
This chapter assumes you can write basic SQL, create tables, manage roles with GRANT, and know that ENABLE ROW LEVEL SECURITY turns a table to default deny. It also assumes you have written a first CREATE POLICY with USING and WITH CHECK. Here you will split one broad policy into separate policies for SELECT, INSERT, UPDATE, and DELETE, and predict which expressions PostgreSQL evaluates for each statement.
Why split a policy by command
A policy created with FOR ALL (the default when you omit FOR) applies the same rule to every command. That is a good start, but real access rules differ by command:
- Everyone on a team may read all tickets, but only the owner may change one.
- Anyone may create a row, but only as themselves.
- Deleting is allowed only for rows in a final state.
Writing one policy per command lets each rule say exactly what it means. It also keeps each expression small, which is easier to review and to test.
The five command forms
CREATE POLICY ... FOR command accepts ALL, SELECT, INSERT, UPDATE, or DELETE. Each form accepts only the expressions that make sense for it. PostgreSQL rejects the others with a syntax error.
| Command | `USING` allowed | `WITH CHECK` allowed | What `USING` or `WITH CHECK` tests |
|---|---|---|---|
| `SELECT` | yes | no | Existing rows to return |
| `INSERT` | no | yes | The new row being inserted |
| `UPDATE` | yes | yes | `USING` tests the existing row, `WITH CHECK` tests the new row |
| `DELETE` | yes | no | Existing rows to remove |
| `ALL` | yes | yes | Applies to every command above |
Two defaults are worth remembering:
- If an
ALLorUPDATEpolicy hasUSINGbut noWITH CHECK, PostgreSQL uses theUSINGexpression for theWITH CHECKside too. - A command with no applicable policy gets no rows, because RLS is default deny. An
INSERTwith no insert policy fails, and anUPDATEwith no update policy changes zero rows.
How failures show up
The two clauses fail in different ways, and this affects how your application sees them.
- A row that fails
USINGis skipped silently. ASELECTomits it. AnUPDATEorDELETEleaves it alone and reportsUPDATE 0orDELETE 0. - A new row that fails
WITH CHECKraises the errornew row violates row-level security policy for table "...". The statement aborts.
Which expressions run for each statement
The rules for UPDATE and DELETE are less obvious than for plain reads and inserts. An UPDATE must find the rows it will change, and it may also read columns in its WHERE clause or RETURNING list. So PostgreSQL combines policies:
- An
UPDATEorDELETEwhoseWHEREorRETURNINGreads column values also needs the existing row to pass aSELECTpolicy. A table with anUPDATEpolicy but noSELECTpolicy can fail on a statement such asUPDATE t SET x = 1 WHERE id = 5, because the statement cannot readid. SELECT ... FOR UPDATEandFOR SHAREneed the row to pass both theSELECTpolicy and theUPDATEpolicy'sUSING.INSERT ... RETURNINGneeds the new row to pass theINSERTpolicy'sWITH CHECKand also theSELECTpolicy'sUSING. If theSELECTcheck fails, you get an error rather than a skipped row.INSERT ... ON CONFLICT DO UPDATEruns theINSERTcheck on the proposed row. If a conflict occurs, it also checks the existing row against theSELECTandUPDATEUSINGexpressions, and the updated row against theUPDATEWITH CHECK.
The diagram follows a single UPDATE ... WHERE statement through the checks.
A worked example: shared tickets
This table lets every user read every ticket but restricts who can write. Run it in a scratch database. The role names ana and ben are new, so they will not clash with roles from other examples.
CREATE TABLE tickets (
id bigserial PRIMARY KEY,
owner_name text NOT NULL DEFAULT current_user,
status text NOT NULL DEFAULT 'open',
title text NOT NULL
);
ALTER TABLE tickets ENABLE ROW LEVEL SECURITY;
CREATE POLICY tickets_select ON tickets
FOR SELECT
USING (true);
CREATE POLICY tickets_insert ON tickets
FOR INSERT
WITH CHECK (owner_name = current_user);
CREATE POLICY tickets_update ON tickets
FOR UPDATE
USING (owner_name = current_user)
WITH CHECK (owner_name = current_user);
CREATE POLICY tickets_delete ON tickets
FOR DELETE
USING (owner_name = current_user AND status = 'closed');Each policy states one rule:
- Anyone with the
SELECTprivilege can read all rows. - A new row must be owned by the inserting role.
- You can update only your own rows, and the result must still be yours. The
WITH CHECKstops you from handing a row to someone else. - You can delete only your own rows, and only when they are closed.
Now exercise the rules with two roles. Policies never replace table privileges. The role needs both the GRANT and a passing policy.
CREATE ROLE ana;
CREATE ROLE ben;
GRANT SELECT, INSERT, UPDATE, DELETE ON tickets TO ana, ben;
GRANT USAGE ON SEQUENCE tickets_id_seq TO ana, ben;
SET ROLE ana;
INSERT INTO tickets (title) VALUES ('Printer jam');
SET ROLE ben;
INSERT INTO tickets (title) VALUES ('Login bug');
SELECT title, owner_name FROM tickets; -- both rows are visible
UPDATE tickets SET status = 'closed'
WHERE title = 'Printer jam'; -- UPDATE 0: not ben's row
DELETE FROM tickets WHERE title = 'Login bug'; -- DELETE 0: still open
SET ROLE ana;
UPDATE tickets SET owner_name = 'ben'
WHERE title = 'Printer jam';
-- ERROR: new row violates row-level security policy for table "tickets"
UPDATE tickets SET status = 'closed'
WHERE title = 'Printer jam'; -- UPDATE 1
DELETE FROM tickets WHERE title = 'Printer jam'; -- DELETE 1
RESET ROLE;Ben's UPDATE finds the row, because the SELECT policy lets him read it. The UPDATE USING expression then rejects it, so zero rows change and no error appears. Ana's attempt to reassign the row passes USING but fails WITH CHECK, so it raises an error.
How multiple policies combine
You can create several policies for the same table and command. By default, policies are permissive, and PostgreSQL combines them with OR. A row is allowed if at least one applicable policy allows it. A FOR ALL policy joins that group for every command, so adding a FOR ALL policy to the ticket table would widen every command's access, not replace the specific policies.
The next chapters cover targeting policies at roles and the restrictive policies that combine with AND. For now, treat each command as having its own OR-group of permissive policies.
Commands that RLS treats specially
A few operations do not map neatly onto the four statements:
COPY table TOfollows theSELECTpolicies.COPY ... FROMfollows theINSERTpolicies.TRUNCATEis not subject to row security. Control it with theTRUNCATEprivilege, which you should withhold from untrusted roles.- Foreign key checks and unique-constraint checks run internally and ignore RLS. They can reveal that a hidden row exists. The pitfalls chapter returns to this.
Choosing between ALL and per-command policies
Use FOR ALL when one predicate truly fits every command, such as "a user owns the row, so the user may do anything to it". The first policy in the earlier examples is of this kind. Use per-command policies when:
- Reading and writing follow different rules, as with the tickets table.
- Only
INSERTneeds to constrain who the new row's owner can be. DELETEhas stricter conditions, such as a status check.- You want each policy's name to document one rule, so that
pg_policiesoutput reads clearly.
Per-command policies also make mistakes easier to find. A missing UPDATE policy shows up as "my update does nothing", which is a narrower search than "something in this big policy is wrong".
Exercise
A table has RLS enabled, a SELECT policy with USING (true), and an UPDATE policy with USING (ownername = currentuser) and no WITH CHECK. The role alice owns row 7. She runs UPDATE t SET owner_name = 'bob' WHERE id = 7. What happens, and why?
Show answer
The statement fails with "new row violates row-level security policy". The existing row passes the UPDATE USING expression, so it is selected. Because the policy has no WITH CHECK, PostgreSQL reuses the USING expression to check the new row. The new row has ownername = 'bob', so ownername = current_user is false for alice, and the update is rejected.
Exercise
Role ben runs DELETE FROM tickets WHERE id = 10 on the tickets table above, where row 10 belongs to ana and is closed. The command reports DELETE 0 and no error. Which part of the delete policy caused this, and why was no error raised?
Show answer
The condition ownername = currentuser in the DELETE policy's USING expression is false for ben, so the row fails the policy. Rows that fail USING are skipped silently, and only a failed WITH CHECK on a new row raises an error. DELETE policies cannot have WITH CHECK at all.
Exercise
You create only an INSERT policy with WITH CHECK (ownername = currentuser) and then run INSERT INTO tickets (title) VALUES ('x') RETURNING id on a table that has no SELECT policy. What do you expect, and what is the fix?
Show answer
The insert is rejected with a row-level security error. RETURNING makes PostgreSQL check the new row against a SELECT policy as well as the INSERT policy, and with no SELECT policy the default deny applies. Add a SELECT policy that allows the role to see its own row, for example FOR SELECT USING (ownername = currentuser), or drop RETURNING.