Sub topic 1
Why row-level security?
Prerequisites
This chapter assumes you already know the following:
- Basic SQL:
SELECT,INSERT,UPDATE,DELETE, andWHEREclauses. - How to create tables and indexes in PostgreSQL.
- PostgreSQL roles, and how
GRANTandREVOKEcontrol privileges. - How to run statements in
psqlor another SQL client.
You need a PostgreSQL server where you can create roles and tables. Row-level security (RLS) has existed since PostgreSQL 9.5. One feature in later chapters, security_invoker views, needs PostgreSQL 15 or later.
The problem RLS solves
Ordinary PostgreSQL privileges work at the level of whole objects. GRANT SELECT ON documents TO alice lets Alice read every row in documents. Column privileges narrow this to chosen columns, but they still apply to every row.
Many applications need a finer rule: "each user sees only their own rows," or "each customer sees only their own company's data." Without database support, the application has to enforce the rule by adding a WHERE clause to every query. That approach has weaknesses:
- One forgotten
WHEREclause leaks data. - Every code path that talks to the database must repeat the rule. This includes reporting scripts, admin tools, and other services.
- Anyone who connects to the database directly, for example with
psql, is not bound by the application's rules.
Row-level security moves the rule into the database. You attach one or more policies to a table. PostgreSQL then applies them to every query against that table, whichever client sent it.
How RLS differs from other mechanisms
| Mechanism | Granularity | Decided by | Typical use |
|---|---|---|---|
| Table privileges (`GRANT`) | Whole table | Role | "Alice may read `documents`" |
| Column privileges | Chosen columns of every row | Role | "Alice may not read `salary`" |
| Views | Whatever the view query selects | View definition | Hiding columns or fixed row subsets |
| Row-level security | Individual rows | Policy expression evaluated per row | "Alice may read only rows she owns" |
RLS does not replace table privileges. The two checks are layered. A role first needs the table privilege (for example SELECT). Then the policies decide which rows that privilege applies to. If a role lacks SELECT on the table, no policy can help it.
What a policy is
A policy is a named rule attached to a table. It holds a boolean expression that PostgreSQL evaluates against rows. A policy can carry two kinds of expression:
USINGdecides which existing rows a command can see or touch. Rows for which the expression is not true are silently skipped.WITH CHECKdecides which new or modified rows may be written. A row that fails the check causes an error.
Later chapters cover these in detail. For now, remember the split. USING filters rows that are already there. WITH CHECK validates rows that are about to be stored.
A first look
The example below creates a table and turns on RLS with one policy. Each role can see and write only the rows whose owner_name equals its own role name.
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);Three things are worth noticing:
owner_namedefaults tocurrent_user, so a new row is stamped with the role that inserted it.ALTER TABLE ... ENABLE ROW LEVEL SECURITYswitches RLS on. Until you run it, policies on the table have no effect.current_useris a built-in function that returns the name of the role currently running the query. Because it is evaluated for each query, the same policy gives different results to different roles.
Seeing it work
You can test the policy by switching roles with SET ROLE. This needs a role that is allowed to switch to the others, such as the superuser that created the table.
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;Here is what happens at each step:
- Alice inserts a row. Her
owner_namedefaults toalice, which passes theWITH CHECKexpression. - Bob selects from the table. The
USINGexpression is false for Alice's row, so Bob sees nothing. He gets no error and no hint that the row exists. - Bob tries to insert a row claiming Alice as the owner. The
WITH CHECKexpression is false, so PostgreSQL rejects the row with an error.
The two failure modes differ on purpose. Reads and the row-selection part of updates and deletes are filtered quietly. Writes that would create a disallowed row fail loudly.
The sequence grants matter too. RLS does not replace them. Without GRANT USAGE ON SEQUENCE documents_id_seq, the bigserial default would fail for Alice and Bob regardless of any policy.
Default deny
Once RLS is enabled on a table, access for ordinary roles is denied by default. If the table has no policy, those roles see no rows and cannot add or change any. A policy then opens up exactly the rows it describes. This is a safer starting point than a filter you must remember to add: forgetting a policy hides data instead of exposing it.
The next chapter covers this behavior in full, including the roles that are exempt.
When RLS is a good fit
RLS suits cases where the row-access rule is stable, simple to express, and must hold no matter which client connects:
- Multi-tenant applications, where many customers share tables and each must see only their own rows.
- Data that is subject to compliance rules, where the database itself should enforce who may see what.
- Systems with several applications or services that share a database, so one application's bug cannot expose another's rows.
- Defense in depth, where RLS acts as a second barrier behind application checks.
When to be careful
RLS is not free, and it does not suit every case:
- Performance. PostgreSQL adds the policy expression to every query on the table. A policy that calls expensive functions or queries other tables can slow every query. Indexes on the columns used in policies help.
- Complexity. Policies live apart from application code. A query can return different results depending on the role, which makes debugging harder. You need a habit of testing with the roles you actually use.
- Exemptions. Superusers, roles with the
BYPASSRLSattribute, and (by default) the table's owner are not subject to policies. A policy protects data only against roles that cannot skip it. - Side channels. RLS hides rows, but error messages, timing, and some constraint checks can still reveal that a hidden row exists. Later chapters cover these cases.
Where this chapter fits
The remaining chapters build the full picture step by step: how default deny works, how to write and combine policies, who bypasses them, how to carry a tenant identity into a policy, and how to test and tune the result.
Exercise
A role has SELECT on a table with RLS enabled, and one policy with USING (owner_name = current_user). The role runs SELECT * FROM documents and gets zero rows, although the table holds many rows owned by other users. Does PostgreSQL raise an error, and why?
Show answer
No error. A USING expression filters existing rows silently, so rows that fail it are skipped as if they did not exist. Only a WITH CHECK failure on a row being written raises an error.
Exercise
Why is RLS not a replacement for GRANT? Give an example of a statement that fails even when a matching policy exists.
Show answer
The two layers are checked together. A role needs the table privilege first, and policies then decide which rows that privilege covers. For example, if a role has a policy allowing its own rows but no INSERT privilege on the table, its INSERT fails with a permission error.
Exercise
Your application connects to the database as the role that owns the documents table, and RLS is enabled with a correct policy. Users report seeing each other's rows. What is the likely cause?
Show answer
Table owners are exempt from RLS by default, so the application's connection skips the policies. Fix it by connecting as a separate unprivileged role, or by running ALTER TABLE documents FORCE ROW LEVEL SECURITY so that the owner is also subject to the policies. Superusers and roles with BYPASSRLS would behave the same way.