Advanced PostgreSQL: Functions, JSON, and SecurityLesson 6.5
How Row Level Security (RLS) works in PostgreSQL
ALTER TABLE ENABLE ROW LEVEL SECURITY, CREATE POLICY, USING clause, WITH CHECK, current_user, current_setting, policy for SELECT INSERT UPDATE DELETE, BYPASSRLS
Row Level Security
RLS restricts which rows a role can see or modify. It is enforced transparently — queries automatically filter based on the current user without any application-layer changes.
Enable RLS
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents FORCE ROW LEVEL SECURITY; -- applies to owner tooCreate policies
-- Users can only see their own documents
CREATE POLICY user_isolation ON documents
FOR ALL
USING (owner_id = current_setting('app.current_user_id')::INT);
-- Separate read and write policies
CREATE POLICY doc_read ON documents FOR SELECT USING (owner_id = current_setting('app.current_user_id')::INT);
CREATE POLICY doc_write ON documents FOR INSERT WITH CHECK (owner_id = current_setting('app.current_user_id')::INT);Set user context
SET app.current_user_id = '42';
SELECT * FROM documents; -- automatically filteredUSING controls which rows are visible (SELECT, UPDATE, DELETE). WITH CHECK controls which rows can be inserted or updated into. Superusers and roles with BYPASSRLS bypass all policies. In a web app, set the session variable per request using SET LOCAL inside a transaction.
