How do you implement row-level security (RLS) in PostgreSQL?
Answer
Row-Level Security (RLS) restricts which rows are visible or modifiable per user, enabling fine-grained access control directly in the database. Enable on a table: ALTER TABLE orders ENABLE ROW LEVEL SECURITY;. Create policies: CREATE POLICY user_isolation ON orders FOR ALL TO app_user USING (user_id = current_user_id());. The USING expression filters SELECT/UPDATE/DELETE; WITH CHECK filters INSERT/UPDATE. Superusers and table owners bypass RLS unless ALTER TABLE ... FORCE ROW LEVEL SECURITY is set. Use SET app.current_user_id = 42 with current_setting('app.current_user_id')::INTEGER to pass the user context. RLS is essential for multi-tenant SaaS applications — it enforces tenant isolation at the database level, preventing application bugs from leaking data.
Previous
What is logical replication in PostgreSQL?
Next
What is table bloat in PostgreSQL and how do you fix it?