Sub topic 1
Row-Level Security in PostgreSQL: Why It Matters and How It Starts
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE, and WHERE), can create tables in PostgreSQL, and understand roles and GRANT. You should have psql or another SQL client and a database where you can create roles.
Why row-level security?
Table privileges decide whether a role can read or change a whole table. Row-level security (RLS) decides which rows a role can see or change inside that table. Without RLS, a role that can SELECT from documents sees every document. With RLS, the same role sees only the rows that a policy allows.
RLS rules are stored as policies attached to a table. PostgreSQL applies them to every query, so the application cannot accidentally skip the filter.
Turning RLS on: default deny
Create a sample table and enable RLS:
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;Once RLS is enabled and no policy exists, a non-owner role sees no rows and cannot insert any. This is default deny. Enabling RLS before writing policies locks the table rather than opening it.
Writing your first policy
A policy names a table, a command, and a condition. This policy lets each role see and change only the rows it owns:
CREATE POLICY documents_owner ON documents
FOR ALL
USING (owner_name = current_user)
WITH CHECK (owner_name = current_user);Test it by switching roles:
CREATE ROLE alice;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO alice;
GRANT USAGE ON SEQUENCE documents_id_seq TO alice;
SET ROLE alice;
INSERT INTO documents (title) VALUES ('Alice notes');
SELECT title FROM documents; -- returns 'Alice notes'
RESET ROLE;USING and WITH CHECK: filtering versus validating rows
USING filters existing rows. It decides which rows a SELECT, UPDATE, or DELETE can see or touch. WITH CHECK validates new rows. It decides whether an INSERT, or the new version of an UPDATE, is allowed.
CREATE ROLE bob;
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO bob;
GRANT USAGE ON SEQUENCE documents_id_seq TO bob;
SET ROLE bob;
SELECT title FROM documents; -- returns no rows: USING hides alice's row
INSERT INTO documents (title, owner_name) VALUES ('Forged', 'alice');
-- ERROR: new row violates row-level security policy for table "documents"
RESET ROLE;> Note: If a policy omits WITH CHECK, PostgreSQL uses the USING expression for new rows. The policy above still validates inserts.
Exercise
A table has RLS enabled and no policies. Role carol runs SELECT * FROM notes. What does she get, and why?
Show answer
She gets zero rows, with no error. RLS is enabled, so default deny applies, and with no policy that allows her access, no rows pass the filter.