Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 153/ 160
08. Transactions, Security & Production SQL Administration

Row-Level Security (RLS) Policies for Multi-Tenant Databases

Enforce tenant isolation with RLS policies evaluated per row.

AdvancedRLS · Policy · Tenant3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

The database itself hides rows that don't belong to you, even if the app forgets to filter them.

Think of it like…

A shared office printer with ID cards: everyone uses the same printer, but each person's badge only releases their own documents, whoever presses the button.

Where you’ve seen it

A SaaS invoicing app keeps all tenants in one invoices table. Each request runs SET LOCAL app.tenant_id = '42' inside its transaction, and the RLS policy ensures every SELECT, UPDATE and DELETE on invoices only touches tenant 42's rows, even if a developer writes SELECT * FROM invoices.

Words you’ll hear

ENABLE ROW LEVEL SECURITY
Turns RLS on for a table; with no policies, normal roles see no rows.
Policy USING
Condition for which existing rows are visible or affected.
Policy WITH CHECK
Condition that new or updated rows must satisfy.
BYPASSRLS / owner
Superusers and roles with BYPASSRLS skip policies; table owners do too unless FORCE is set.

Visual diagram

Loading interactive diagram

Theory & example queries

Enabling RLS and writing policies

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY; turns enforcement on; from then on, ordinary roles see no rows until a policy allows them. A policy can apply to all commands or to specific ones (SELECT, INSERT, UPDATE, DELETE) and specific roles. USING filters which existing rows are visible or modifiable; WITH CHECK validates rows being inserted or updated, so a tenant can't write a row tagged with another tenant's id.

The policy needs to know who the current user or tenant is. Common approaches: a database role per user (current_user), or a session setting the application sets per request, such as current_setting('app.tenant_id'). Supabase uses auth.uid() from a JWT in the same way.

Tenant isolation for reads and writesQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;23CREATE POLICY tenant_isolation ON invoices USING (4  tenant_id = current_setting('app.tenant_id')::bigint5)6WITH7  CHECK (8    tenant_id = current_setting('app.tenant_id')::bigint9  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command responses2 sample rows
Representative command responses
statementstatus
ENABLE ROW LEVEL SECURITYALTER TABLE
CREATE POLICYCREATE POLICY

Note: PostgreSQL returns these command tags when the statements succeed for a table the role owns. Policy checks are evaluated later for queries by non-owner roles.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: USING for visibility, WITH CHECK for writes, a session setting for the tenant.

Pitfalls in production

Superusers and roles with BYPASSRLS ignore policies, and so does the table's owner unless you run ALTER TABLE … FORCE ROW LEVEL SECURITY. The application should connect as a separate, non-owner role. With connection pooling (especially PgBouncer in transaction mode), set the tenant with SET LOCAL inside each transaction so the setting can't leak to the next request that reuses the connection.

Policies run as extra conditions on every query, so index tenant_id (usually as the leading column of composite indexes) and keep policy expressions simple. Test policies explicitly: connect as the application role with different tenant settings and check that cross-tenant reads and writes fail. SQL Server has a comparable security-policy feature; MySQL has no built-in row-level security.

Per-request tenant settingQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1BEGIN;23SET4  LOCAL app.tenant_id = '42';56SELECT7  *8FROM9  invoices10WHERE11  status = 'unpaid';1213COMMIT;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Start transaction

Open a transaction so changes can be checked and committed or rolled back together.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative tenant-42 invoices2 sample rows
Representative tenant-42 invoices
idtenant_idstatusamount
70142unpaid199.99
71442unpaid85

Note: The sample assumes an RLS policy for tenant 42 and two unpaid invoices. PostgreSQL responds BEGIN, SET and COMMIT around the SELECT; after COMMIT the local tenant setting is no longer available.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The setting disappears at COMMIT, so the next request on this connection starts clean.

Key takeaway: Non-owner app role, SET LOCAL per transaction, index tenant_id, test cross-tenant access.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Schema

Add tenant_id everywhere

Every tenant-owned table needs a tenant_id column, indexed (often as the first column of composite indexes).

Focus at this step

tenant_id bigint NOT NULL

What to watch at this step
Index
tenant_id first
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Row-level security (RLS) lets the database decide, per row, what each user or tenant can see and change. In PostgreSQL you enable it on a table and add policies: CREATE POLICY tenant_isolation ON invoices USING (tenant_id = current_setting('app.tenant_id')::bigint). Every query on the table then gets that condition added automatically, so a missing WHERE in application code can't leak another tenant's data.

Why it matters: In multi-tenant SaaS apps, one forgotten WHERE tenant_id = ? exposes customers' data to each other. RLS moves that rule into the database, where every query path (APIs, scripts, reporting tools) is covered. It's increasingly common, Supabase is built around it, and it comes up in security and SaaS architecture interviews.

When to reach for it

  • Multi-tenant SaaS on a shared schema
  • User-owned rows exposed through APIs (as in Supabase)
  • Defence in depth behind application checks

When to avoid or be careful

  • Running the app as the table owner or a superuser
  • Plain SET (not SET LOCAL) for tenant ids with pooled connections
  • Complex, slow policy expressions without supporting indexes

RLS vs application filters vs separate databases

Row-level security
Best for: Multi-tenant apps on a shared schema

Strengths: Enforced on every query path; can't be forgotten.

Watch out: Policies add complexity; owner and superuser bypass; needs careful pooling.

WHERE tenant_id = ? in application code
Best for: Simple apps with one data-access layer

Strengths: Easy to understand.

Watch out: One missed filter leaks data.

Schema or database per tenant
Best for: Few large tenants with strict isolation needs

Strengths: Strong isolation; per-tenant backups.

Watch out: Migrations and operations multiply with tenant count.

Interview signals & numbers to know

When this topic comes up

  • “Ensure tenants can't see each other's data”
  • Multi-tenant SaaS design
  • Supabase policies
  • Data leak through a missing WHERE
  • Defence in depth

Benchmarks & rules of thumb

0 rows -
visible after enabling RLS without a policy
USING / WITH CHECK -
read and write conditions
PostgreSQL 9.5 -
RLS introduced

Common mistakes & follow-ups

Common interview mistakes

  • Testing RLS as the table owner and concluding it doesn't work.
  • Using SET app.tenant_id with PgBouncer transaction pooling, so the next request inherits the previous tenant.
  • Adding a USING policy but no WITH CHECK, letting users insert rows for other tenants.

Likely interviewer follow-ups

  • How would you isolate tenants in a shared PostgreSQL database?
  • Why might RLS appear not to work when you test it?
  • How do you pass the current tenant to the database safely with a connection pool?
Interview tip: Show the policy, then cover the three production details: non-owner role, SET LOCAL with pools, and an index on tenant_id. Those details are what make the answer credible.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Row-Level Security (RLS) Policies for Multi-Tenant Databases with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Users, Roles & Privilege Management (GRANT, REVOKE)
Next topic
Preventing SQL Injection (Parameterized Queries & Prepared Statements)