How to implement row level security in PostgreSQL
· Category: SQL & Databases
Short answer
Row-Level Security (RLS) allows you to define policies that control which rows a user can see or modify, automatically enforced on every query.
Steps
- Enable RLS on a table:
ALTER TABLE documents ENABLE ROW LEVEL SECURITY; - Create a policy:
CREATE POLICY user_isolation ON documents FOR SELECT USING (owner = current_user); - Define separate policies for
SELECT,INSERT,UPDATE, andDELETE. - Use
FORCE ROW LEVEL SECURITYto apply policies even to table owners. - Test with different roles to ensure policies behave as expected.
Tips
- Combine RLS with application-level user IDs stored in
current_settingfor multi-tenant apps. - Policies can reference other tables, but be mindful of performance and recursion.
Common issues
- Superusers and table owners bypass RLS by default unless forced.
- Complex policies with subqueries can introduce significant query overhead.r