🚀AdvancedSecurity
Row-Level Security (RLS)
Restrict which rows users can see or modify using Row-Level Security policies.
Overview
Row-Level Security (RLS) allows you to define fine-grained access control at the row level different users see or can modify different subsets of rows in the same table. This is essential for multi-tenant applications, data privacy compliance, and least-privilege data access.
Enable RLS with ALTER TABLE t ENABLE ROW LEVEL SECURITY, then define policies with CREATE POLICY. Policies are automatically applied to every query users only see rows where the policy condition is TRUE. Table owners bypass RLS by default unless FORCE ROW LEVEL SECURITY is set.
Key Points
- •ALTER TABLE t ENABLE ROW LEVEL SECURITY enables RLS
- •CREATE POLICY name ON t USING (condition) define row filter
- •Separate policies for SELECT, INSERT, UPDATE, DELETE
- •current_user or app.user_id for multi-tenant filtering
- •FORCE ROW LEVEL SECURITY also applies to table owners
- •WITH CHECK additional condition for INSERT/UPDATE rows
Examples
Multi-tenant RLS
-- Enable RLS
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-- Users see only their own orders
CREATE POLICY orders_user_policy ON orders
USING (user_id = current_user::INTEGER);
-- Or using a session variable for app-level multi-tenancy
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::INTEGER);
-- Admin bypass
CREATE POLICY admin_all ON orders
TO admin_role
USING (TRUE); -- admin sees all rowsExercises
Write SQL to solve each exercise. Your progress is saved automatically.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4