Dev tools
Row Level Security in Postgres: A Practical Guide
Row level security in Postgres explained: how RLS policies work, USING vs WITH CHECK, multi tenant and Supabase examples, performance and pitfalls.
Row level security (RLS) is a database feature that restricts which rows each user can read or change, enforced by the database itself rather than by application code. In PostgreSQL you enable it per table and write policies, SQL conditions such as "tenant_id equals the current tenant", that are automatically added to every query. Once RLS is on and no policy matches, the default is to show nothing. It's widely used for multi tenant SaaS and is essential in Supabase, where browsers can query the database through an API.
This guide explains what row level security is, how a Postgres RLS policy works (USING vs WITH CHECK, permissive vs restrictive), a step-by-step setup, a Postgres row level security multi tenant example, Supabase row level security, performance tips, how to test policies, and the pitfalls that leak data.
What Is Row Level Security?
What is row level security, in plain terms? Ordinary database permissions work at the table level: a role can SELECT from a table or not. Row level security adds a filter inside the table: a role may be allowed to SELECT from invoices, but only sees invoices whose tenant_id matches its own.
PostgreSQL has supported row security policies since version 9.5. The key behaviours, from the official documentation:
- RLS is enabled per table with
ALTER TABLE ... ENABLE ROW LEVEL SECURITY. - Once enabled, all normal access to the table for selecting or modifying rows must be allowed by a policy. If no policy exists, a default-deny policy applies: no rows are visible or can be modified.
- Operations that apply to the whole table, such as
TRUNCATEandREFERENCES, aren't subject to row security. - Superusers and roles with the `BYPASSRLS` attribute always bypass row security. Table owners normally bypass it too, unless the table is set to
FORCE ROW LEVEL SECURITY. - Policy expressions run as part of the query with the privileges of the user running the query.
Other databases have similar features under the same name, including SQL Server, Snowflake, Databricks and BI tools such as Power BI, but this guide focuses on PostgreSQL.
Why Use Row Level Security?
- Defence in depth. Even if application code forgets a
WHERE tenant_id = ...filter, the database won't return another tenant's rows. - One rule, everywhere. The same policy applies to your API, background jobs, reporting tools and ad-hoc queries that use the restricted role.
- Direct client access. Platforms such as Supabase and PostgREST let browsers and mobile apps query tables through an API; RLS is what keeps users to their own data.
- Simpler application code. Queries can be written without repeating tenant and ownership filters (though keeping them in the app as well is a good practice).
Row level security is a form of authorization, the "what can you access" step that comes after authentication; our authentication vs authorization guide explains the difference.
How a Postgres RLS Policy Works
A Postgres RLS policy is created with CREATE POLICY. Its main parts:
CREATE POLICY policy_name ON table_name
[ AS { PERMISSIVE | RESTRICTIVE } ]
[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
[ TO { role_name | PUBLIC | CURRENT_USER } ]
[ USING ( expression_for_existing_rows ) ]
[ WITH CHECK ( expression_for_new_rows ) ];| Part | Meaning |
|---|---|
FOR | Which commands the policy covers; defaults to ALL |
TO | Which roles it applies to; defaults to PUBLIC (everyone) |
USING | A condition on existing rows: which rows are visible to SELECT and which can be targeted by UPDATE and DELETE |
WITH CHECK | A condition on new or changed rows: which rows INSERT and UPDATE may write |
PERMISSIVE (default) | Permissive policies are combined with OR: a row is allowed if any of them allows it |
RESTRICTIVE | Restrictive policies are combined with AND: every one must allow the row, on top of at least one permissive policy |
USING vs WITH CHECK is the distinction people trip over most. USING filters what a user can see and touch; WITH CHECK validates what they're trying to write. Without WITH CHECK on an UPDATE policy, PostgreSQL applies the USING expression to new rows as well, but being explicit avoids surprises, such as a user moving a row into another tenant.
| Command | Uses USING? | Uses WITH CHECK? |
|---|---|---|
| SELECT | Yes | No |
| INSERT | No | Yes |
| UPDATE | Yes (rows that can be updated) | Yes (what the updated row may look like) |
| DELETE | Yes | No |
How to Set Up Row Level Security Step by Step
Here's a minimal setup where each user can only see and edit their own notes, adapted from the patterns in the PostgreSQL documentation:
CREATE TABLE notes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
owner text NOT NULL DEFAULT current_user,
body text NOT NULL
);
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
CREATE POLICY notes_owner ON notes
FOR ALL
TO PUBLIC
USING (owner = current_user)
WITH CHECK (owner = current_user);
GRANT SELECT, INSERT, UPDATE, DELETE ON notes TO alice, bob;Now when the database role alice runs SELECT * FROM notes, PostgreSQL silently adds WHERE owner = current_user, and she sees only her rows. If she tries to insert a note with owner = 'bob', the WITH CHECK condition rejects it.
Steps in short:
- Decide the rule in plain words: "users see their own rows", "members see their organisation's rows", "managers see their team's rows".
- Make sure the data supports it: a
tenant_id,ownerorteam_idcolumn on every protected table. - Enable RLS on each table.
- Write policies per command, or one
FOR ALLpolicy with bothUSINGandWITH CHECK. - Connect as a role that doesn't bypass RLS: not a superuser, not
BYPASSRLS, not the table owner (or setFORCE ROW LEVEL SECURITY). - Grant table privileges to that role; RLS filters rows but doesn't replace ordinary
GRANTpermissions. - Test by switching roles and checking what each can see and change.
Postgres Row Level Security Multi Tenant Example
In most web applications, end users aren't database roles: the app connects with one role and many users share it. For Postgres row level security multi tenant setups, the usual pattern is to pass the current tenant through a session setting:
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id uuid NOT NULL,
amount numeric(12,2) NOT NULL
);
CREATE INDEX invoices_tenant_idx ON invoices (tenant_id);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
TO app_user
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);For each request, the application opens a transaction and sets the tenant only for that transaction:
BEGIN;
SELECT set_config('app.tenant_id', '6f1c2a4e-0000-4000-8000-000000000001', true); -- true = local to this transaction
SELECT * FROM invoices; -- returns only that tenant's invoices
COMMIT;Passing true as the second argument to current_setting makes it return NULL instead of raising an error when the setting is missing. A comparison with NULL is never true, so a request that forgets to set the tenant sees nothing rather than everything: a safe failure. Setting the value with set_config(..., true) (or SET LOCAL) keeps it scoped to the transaction, which matters with connection poolers such as PgBouncer in transaction mode, where the next transaction on the same connection may belong to another tenant.
Worked example: what each request sees
The invoices table holds five rows for two tenants, A and B. The app role app_user doesn't bypass RLS.
| Request | Tenant setting | Query | Rows returned |
|---|---|---|---|
| User from tenant A lists invoices | A | SELECT * FROM invoices | Tenant A's 3 rows |
| User from tenant B lists invoices | B | SELECT * FROM invoices | Tenant B's 2 rows |
| Bug: tenant not set | none (NULL) | SELECT * FROM invoices | 0 rows |
| Tenant A user tries to insert a row for tenant B | A | INSERT ... (tenant_id = B) | Rejected by WITH CHECK |
| Migration run as the table owner | any | SELECT count(*) FROM invoices | All 5 rows (owner bypasses RLS unless FORCE is set) |
The last row is the classic surprise: if your application connects as the table owner, RLS does nothing unless you add ALTER TABLE invoices FORCE ROW LEVEL SECURITY.
Supabase Row Level Security
Supabase row level security is the same PostgreSQL feature, but it matters even more there because Supabase exposes tables through an auto-generated API that browsers call with a public key. Without RLS on an exposed table, anyone with that key can read or write it.
Supabase provides helper functions that read the logged-in user from the request's JWT, notably auth.uid(). A typical policy:
alter table profiles enable row level security;
create policy "Users can view their own profile"
on profiles for select
to authenticated
using ( (select auth.uid()) = id );Supabase's documentation recommends a few practices for performance and safety:
- Name the role with
to authenticated(oranon), so the policy doesn't run for users it doesn't apply to. - Wrap the function in a subselect,
(select auth.uid()), instead of callingauth.uid()directly, so Postgres can evaluate it once per query rather than once per row. - Index every column your policies filter on, because Postgres evaluates the policy against each candidate row; an unindexed filter turns reads into sequential scans.
- Use security definer functions for checks that need to read other tables, such as team membership.
- Test policies with pgTAP through the Supabase CLI.
If you're choosing a backend, our Supabase vs Firebase comparison covers how Supabase's RLS model compares with Firebase's security rules.
Team and Role-Based Policies
Real applications usually need more than "own rows only". Policies can call functions and subqueries, for example letting members of an organisation see its projects:
CREATE POLICY members_read ON projects
FOR SELECT
TO app_user
USING (
org_id IN (
SELECT org_id FROM memberships
WHERE user_id = current_setting('app.user_id', true)::uuid
)
);For complex rules, move the logic into a STABLE function (or a security definer function with care) and index the membership table. You can combine row level security with roles and attributes; our RBAC vs ABAC guide covers how to model those rules, and RLS is one place to enforce them.
Performance Tips
- Index policy columns such as
tenant_id,ownerand membership keys. - Keep policy expressions simple and avoid per-row function calls; precompute values with subselects or session settings.
- Mark helper functions correctly (
STABLEwhen they don't change within a statement) so the planner can optimise. - Check plans with
EXPLAIN ANALYZEas the restricted role, since the policy is part of the plan. - Beware leaky functions: PostgreSQL can't push some conditions past RLS checks unless functions are marked
LEAKPROOF, which can affect index use.
How to Test Row Level Security
- Switch roles in a test database:
SET ROLE app_user;then set the tenant and run queries, checking both what's returned and what's rejected. - Write automated tests that log in as tenant A and attempt to read, update and delete tenant B's rows; run them in CI.
- Test the failure modes: missing tenant setting, NULL values, owner connections and views.
- List policies with
\d+ table_namein psql or by queryingpg_policies, and review them in code review like any other security code.
Common Pitfalls
- Connecting as the table owner or a superuser, so policies never apply.
- Enabling RLS with no policies and wondering why the table looks empty (that's the default deny working).
- Forgetting WITH CHECK, allowing users to write rows they can't later see, or move rows between tenants.
- Views that bypass RLS. By default a view accesses underlying tables with the view owner's privileges, so it can skip the caller's policies. On PostgreSQL 15 and later, create views
WITH (security_invoker = true)so the caller's permissions and policies apply. - Session settings that leak across pooled connections when set with plain
SETinstead ofSET LOCALor transaction-localset_config. - Security definer functions that return data from other tenants because they run with elevated privileges.
- Relying on RLS alone. Keep tenant filters in application queries as well, and keep sensitive operations behind server-side checks.
FAQ
Does row level security slow down queries?
It adds the policy's condition to each query, so the cost depends on that condition. With indexed columns and simple expressions, the overhead is usually small; complex subqueries or per-row function calls can slow queries noticeably.
What's the difference between row level security and column level security?
Row level security controls which rows a user can access; column level security controls which columns they can see. PostgreSQL handles column permissions with column-level GRANT statements, separately from RLS policies.
Can row level security work with connection pooling?
Yes, if the tenant or user identity is set per transaction (with SET LOCAL or transaction-local set_config) rather than per session, so it can't carry over to another request on the same connection.
Do I still need authorization checks in my application with RLS?
It's wise to keep them. RLS is a strong safety net and essential when clients query the database directly, but application checks give clearer error messages and protect operations RLS doesn't cover.
Why does my table return no rows after enabling RLS?
Because enabling row level security with no matching policy applies a default deny. Add a policy that allows the rows the role should see, and make sure the role and session settings match the policy's conditions.