Home / Learn Secure SQL / Row-Level Security
Row-Level Security
Restricting which rows an account (or user) can see, inside the database itself.
Breaking it down
Definition
Row-level security (RLS), supported natively by PostgreSQL and some other databases, lets you define a policy so that queries automatically only see rows matching a condition (e.g. "only rows where tenant_id = current user's tenant"), enforced by the database regardless of how the query was written.
Why you need this
RLS is a powerful defense-in-depth layer for multi-tenant systems: even if application code has a bug that forgets a "WHERE tenant_id = ?" filter, the database itself still refuses to return another tenant's rows.
How it works
Enable RLS on the table, define a policy tying visible rows to a session variable or the connected user's role, and set that session context correctly whenever your application connects.
Where you'll see this
- Web application code review
- Backend development
- Database administration
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::int);
-- Every query against orders is now automatically filtered by tenant_id,
-- even one that forgot to add that condition itselfTest what you just read
1. Row-level security mainly protects against...
A database-enforced backstop filter.