Schemas, search_path & Multitenancy in SQL
Namespaces that isolate tenants without extra clusters
A database holds schemas (namespaces); schemas hold tables/views/functions — sales.orders vs hr.employees. search_path resolves unqualified names (public by default in PG). Multi-tenant patterns: separate schemas per tenant (strong isolation, migration fan-out) vs shared tables + tenant_id + RLS (cheap, policy-dependent). MySQL conflates DATABASE/SCHEMA; PG nests them.
Namespace tables
sales.orders vs hr.employees — same names coexist per schema.
Resolve via search_path
Per-request path selects tenant namespace for bare names.
Tenant pattern pick
Schemas isolate (migration fan-out); shared+RLS economizes (policy risk).
Grant per namespace
Default-deny new schemas; default privileges auto-cover future tables.
1CREATE SCHEMA sales;2CREATE TABLE sales.orders (id INT PRIMARY KEY, total NUMERIC);
| object | scope |
|---|---|
| sales.orders | namespaced table |
| hr.employees | separate namespace |
Identical table names coexist per schema. Per-tenant schemas isolate dumps and grants; shared-schema + RLS isolates rows without migration fan-out.
Two namespaces
Identical names, separate scopes.
1CREATE SCHEMA sales;2CREATE TABLE sales.orders (id INT PRIMARY KEY);
| object | scope |
|---|---|
| sales.orders | sales scope |
| hr.employees | hr scope |
Tenant isolation pick
Fan-out vs policy cost.
1-- schemas-per-tenant: strong iso, N migrations2-- shared + RLS: 1 migration, policy-enforced
| pattern | trade |
|---|---|
| schemas | isolated, fan-out |
| shared+RLS | cheap, policy-tested |
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.