Row-Level Security (RLS) in SQL
Database-enforced tenant isolation — survives buggy queries
PostgreSQL RLS policies (USING for reads, WITH CHECK for writes) enforce per-role row visibility inside the engine — tenant_id = current_setting('app.tenant'). Views with security_barrier plus roles work elsewhere. Tenant-id columns plus policies give multi-tenant isolation that survives every buggy query and leaked connection.
Enable per table
ALTER TABLE … ENABLE ROW LEVEL SECURITY — no policy means no rows (deny by default).
USING gates reads
tenant_id = current_setting(app.tenant) appended invisibly to every read.
WITH CHECK gates writes
Inserts/updates cannot smuggle other tenants’ rows.
Test per role
Same SELECT, different sessions — policy bugs leak silently without role tests.
1-- PostgreSQL RLS:2CREATE POLICY tenant_iso ON orders USING (tenant_id = current_setting('app.tenant')::int);
| session | visibility |
|---|---|
| tenant_7 session | sees tenant_7 rows only |
| tenant_9 session | sees tenant_9 rows only |
Same SELECT text returns different rows per session setting. A forgotten WHERE tenant_id = … no longer leaks — the policy appends it invisibly and un-bypassably.
Tenant isolation policy
Database, not app, guarantees separation.
1CREATE POLICY tenant_iso ON orders USING (tenant_id = current_setting('app.tenant')::int);
| session | visibility |
|---|---|
| tenant_7 | own rows only |
| tenant_9 | own rows only |
Write guard twin
Cannot insert sideways.
1CREATE POLICY tenant_write ON orders FOR INSERT WITH CHECK (tenant_id = current_setting('app.tenant')::int);
| write | verdict |
|---|---|
| own tenant insert | allowed |
| foreign insert | rejected |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.