Sub topic 4
USING and WITH CHECK: Filtering Versus Validating Rows
This chapter assumes you can write basic SQL and have run ALTER TABLE ... ENABLE ROW LEVEL SECURITY and CREATE POLICY once. It also assumes you know how to create roles and GRANT privileges, and that you can switch roles in psql. The chapter covers the two expressions a policy can carry, which commands use each one, and how to read the two ways a policy can reject a row.
Two expressions, two jobs
A policy can have two boolean expressions.
USINGapplies to rows that already exist in the table. It decides which existing rows a command may see, update, or delete. Rows that fail it are silently left out, as if they were not there.WITH CHECKapplies to rows that a command is about to write. It decides whether a new row, or the new version of an updated row, is allowed to be stored. A row that fails it aborts the statement with an error.
So USING filters and WITH CHECK validates. The difference shows up in what you observe. A failed USING leaves no trace, and a failed WITH CHECK raises this error:
ERROR: new row violates row-level security policy for table "documents"An expression that evaluates to NULL counts as a failure in both cases. This matters when a policy compares against a column or setting that can be NULL.
Which command uses which expression
Each command touches existing rows, new rows, or both, so each policy command type accepts a different set of expressions.
| Policy command | `USING` (existing rows) | `WITH CHECK` (new rows) |
|---|---|---|
| `SELECT` | Yes. Filters the rows returned. | Not allowed. |
| `INSERT` | Not allowed. | Yes. Validates the inserted row. |
| `UPDATE` | Yes. Picks which rows can be updated. | Yes. Validates the row after the change. |
| `DELETE` | Yes. Picks which rows can be deleted. | Not allowed. |
| `ALL` | Yes. Used for reads, updates, and deletes. | Yes. Used for inserts and updates. |
UPDATE is the only single command that uses both expressions, and the order is fixed. PostgreSQL first uses USING to find the rows that may be modified. It then computes the new row values and tests each one against WITH CHECK.
The default: one expression covers both
You can write a policy with only USING. When a policy applies to ALL or UPDATE and has no WITH CHECK, PostgreSQL reuses the USING expression as the check. The policy from the spine therefore spells out something that would also hold if you dropped the WITH CHECK line:
CREATE TABLE documents (
id bigserial PRIMARY KEY,
owner_name text NOT NULL DEFAULT current_user,
title text NOT NULL,
body text
);
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY documents_owner ON documents
FOR ALL
USING (owner_name = current_user)
WITH CHECK (owner_name = current_user);Writing both explicitly costs a line and removes doubt about what the policy enforces. You must write WITH CHECK yourself as soon as the two rules differ, as in the example later in this chapter.
INSERT has no existing row, so an INSERT policy takes only WITH CHECK. Giving it USING is a syntax error. SELECT and DELETE policies are the reverse and take only USING.
Watching both expressions fail
Run the setup below as the table owner or a superuser. It creates two roles and grants them table privileges. Row-level security sits on top of ordinary privileges, so a role needs both a GRANT and a passing policy.
CREATE ROLE alice;
CREATE ROLE bob;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO alice, bob;
GRANT USAGE ON SEQUENCE documents_id_seq TO alice, bob;
SET ROLE alice;
INSERT INTO documents (title) VALUES ('Alice notes');
SET ROLE bob;
SELECT title FROM documents; -- returns no rows
INSERT INTO documents (title, owner_name) VALUES ('Forged', 'alice');
-- ERROR: new row violates row-level security policy for table "documents"
RESET ROLE;Bob's SELECT returns nothing because USING hides Alice's row. No error is raised, and nothing tells Bob that a row exists. Bob's INSERT fails loudly because he tried to store a row owned by alice. The DEFAULT current_user on owner_name is what lets an ordinary insert pass: if Bob omits the column, the new row gets bob and satisfies the check.
A policy where the two expressions differ
Consider a blog where anyone can read published posts, authors can read and edit their own drafts, and authors may not publish a post themselves. Publishing is done by a privileged process outside these roles. The rule "edit your own rows, but the result must stay unpublished" needs different expressions for the old and the new row.
CREATE TABLE posts (
id bigserial PRIMARY KEY,
author text NOT NULL DEFAULT current_user,
title text NOT NULL,
published boolean NOT NULL DEFAULT false
);
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
CREATE POLICY posts_read ON posts
FOR SELECT
USING (published OR author = current_user);
CREATE POLICY posts_insert ON posts
FOR INSERT
WITH CHECK (author = current_user AND NOT published);
CREATE POLICY posts_update ON posts
FOR UPDATE
USING (author = current_user)
WITH CHECK (author = current_user AND NOT published);
GRANT SELECT, INSERT, UPDATE ON posts TO alice, bob;
GRANT USAGE ON SEQUENCE posts_id_seq TO alice, bob;Now exercise it:
SET ROLE alice;
INSERT INTO posts (title) VALUES ('Draft');
UPDATE posts SET title = 'Better draft' WHERE title = 'Draft';
-- UPDATE 1
UPDATE posts SET published = true WHERE title = 'Better draft';
-- ERROR: new row violates row-level security policy for table "posts"
SET ROLE bob;
UPDATE posts SET title = 'Hijack' WHERE title = 'Better draft';
-- UPDATE 0
RESET ROLE;The three updates fail or succeed for different reasons:
- Alice's title change passes
USING(she is the author) andWITH CHECK(the author is unchanged and the post is still unpublished). - Alice's publish attempt passes
USINGbut the new row haspublished = true, soWITH CHECKrejects it with an error. - Bob's update never reaches
WITH CHECK. The draft is not published and not his, so theSELECTpolicy hides it. TheUPDATEfinds no candidate rows and reportsUPDATE 0.
Interactions that surprise people
A few rules link the policy types, and they cause most of the confusing results.
UPDATEandDELETEalso consultSELECTpolicies. If the statement'sWHEREclause or itsRETURNINGclause reads column values, the rows must also pass the table'sSELECTUSINGexpressions. That is why Bob's update above found nothing even before theUPDATEpolicy was considered. AnUPDATEwith noWHEREand noRETURNINGthat reads columns needs only theUPDATEpolicy.INSERT ... RETURNINGneeds aSELECTpolicy that admits the new row. If the inserted row would be invisible to the role, the statement fails with a policy violation even though theINSERTcheck passed.INSERT ... ON CONFLICT DO UPDATEchecks existing rows with error semantics. TheINSERTpath validates new rows againstINSERTWITH CHECK. If the conflict path updates an existing row, that row must satisfy theUPDATEandSELECTUSINGexpressions. A row that fails raises an error instead of being skipped.- Several policies for one command combine. With the default permissive policies, a row passes if any one policy's expression is true, and the same holds separately for
USINGandWITH CHECK. The next chapters cover combining policies, including restrictive ones. - The
WITH CHECKofUPDATEsees the new row only. It does not compare old and new values. A rule such as "the owner must not change" cannot be written with a plain comparison between the two. You can only constrain what the new row looks like, so the usual approach is aWITH CHECKon the owner column, as in the examples above.
Choosing the right shape
Use these criteria when you write a policy.
- If the rule is "who can see or touch which rows", write
USING. - If the rule is "what a written row is allowed to look like", write
WITH CHECK. - If a rule is the same for both and the command is
ALL, one expression is enough, but writing both keeps the intent visible. - If a rule differs by command, create one policy per command. That keeps each policy small and lets the reader see which expression applies where.
Exercise
A policy on a table tasks is CREATE POLICY t ON tasks FOR UPDATE USING (assignee = current_user); with no WITH CHECK. Role carol owns a task and runs UPDATE tasks SET assignee = 'dave' WHERE id = 1;. Does the statement succeed? Assume carol can also see the row through a SELECT policy.
Show answer
It fails. Because the policy has no WITH CHECK, PostgreSQL reuses the USING expression as the check. The new row has assignee = 'dave', which does not equal current_user (carol), so the statement raises "new row violates row-level security policy for table". The USING test passed on the old row, but the check on the new row did not.
Exercise
A role runs DELETE FROM documents WHERE id = 42; on a table where a USING expression hides row 42 from that role. Does the role get an error? What does the statement report?
Show answer
There is no error. A DELETE policy uses only USING, and rows that fail it are silently skipped, so the statement reports DELETE 0. WITH CHECK applies only to rows being written, so it never runs here.