PostgreSQL row-level security only protects data when it is switched on for the table, the policies cover every command, and the role that actually connects is not one of the roles that silently bypass it. This guide explains how policies are evaluated, which roles skip them, how to build a tenant isolation model that holds up, and the mistakes that most often turn row-level security into a false sense of safety.
Facts on this page come from the PostgreSQL 18 documentation (current release 18.7 at the time of writing) and, for the platform section, Supabase's public documentation. For the full PostgreSQL hardening picture, including roles, pg_hba.conf and audit logging, see the PostgreSQL Security Guide. For when to use row filtering versus value masking, see Dynamic Data Masking vs Row-Level Security. This page goes deep on row-level security only.
Key takeaways
- Row-level security is off until you enable it per table. Policies have no effect until
ALTER TABLE ... ENABLE ROW LEVEL SECURITYruns on that table. - Enabled with no policy means deny. PostgreSQL applies a default-deny policy, so no rows are visible or modifiable.
- Three kinds of role bypass policies. Superusers and roles with
BYPASSRLSalways bypass, and table owners normally bypass unless you setFORCE ROW LEVEL SECURITY. - The application must not connect as the owner. The most common real failure is an application role that owns the tables, so every policy is skipped.
- Write both
USINGandWITH CHECK.USINGfilters which rows a command can see;WITH CHECKcontrols which rows it can write. Missing the second lets users write rows into another tenant. - Constraints and views leak. Unique and foreign key checks bypass policies, and views run with the view owner's rights unless created with
security_invoker.
How row-level security works
By default a PostgreSQL table has no policies, so any role with SQL privileges on the table sees every row. Row-level security adds a second check after the normal privilege system. Once enabled, each query against the table has the applicable policy expressions added to it, and only rows for which the expression is true are returned or changed.
The documentation is explicit about evaluation order. A policy expression is evaluated for each row before any conditions or functions from the user's query. The only exception is functions marked LEAKPROOF, which the optimiser may run ahead of the policy check because they are guaranteed not to leak information. Policy expressions run with the privileges of the user running the query, so that user needs access to any tables or functions the policy references. Security definer functions can be used to reach data the caller cannot read directly.
Some operations are never subject to row security. Whole-table operations such as TRUNCATE and REFERENCES ignore policies, so table privileges still matter: a role that can TRUNCATE can empty every tenant's rows at once.
Enabling or disabling row security, and adding policies, is always the privilege of the table owner. You must own a table to create or change its policies. That makes the owner role the control plane for row-level security, and it should be treated as an administrative identity, not an application identity.
Writing policies: USING, WITH CHECK and commands
CREATE POLICY takes a name, a table, an optional command (ALL, SELECT, INSERT, UPDATE or DELETE), an optional list of roles, and up to two expressions.
USINGdecides which existing rows the command can see or act on. Rows that fail are filtered out silently.WITH CHECKdecides which new or changed rows may be stored. Rows that fail raise an error and abort the whole command.
If a policy has only USING, PostgreSQL uses the same expression for WITH CHECK. That default is safe for simple ownership rules, but it hides intent; writing both clauses makes review easier.
| Command | Expressions allowed | What they do |
|---|---|---|
SELECT | USING only | Filters visible rows |
INSERT | WITH CHECK only | Checks each new row; a failing row aborts the command |
UPDATE | USING and WITH CHECK | Filters rows to update, then checks the new row values |
DELETE | USING only | Filters rows that can be deleted |
ALL | Both | Applies to every command |
Two details catch teams out. First, an UPDATE or DELETE that reads columns, for example in a WHERE or RETURNING clause, also needs the rows to pass a SELECT or ALL policy. A table with an UPDATE policy but no SELECT policy will appear to update nothing. Second, rows returned through RETURNING must satisfy the SELECT policies, and PostgreSQL raises an error rather than silently dropping them. MERGE has no policy of its own; the SELECT, INSERT, UPDATE and DELETE policies apply according to the actions it performs.
A minimal ownership policy looks like this:
ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;
CREATE POLICY account_managers ON accounts TO managers USING (manager = current_user);
If no role is named, or PUBLIC is used, the policy applies to all roles.
Permissive and restrictive policies
Policies are permissive by default. Permissive policies for the same command are combined with OR: a row is visible if any of them allows it. Restrictive policies, created with AS RESTRICTIVE, are combined with AND: a row must pass all of them. The two groups are then combined with AND. If there are no permissive policies at all, access is denied, so a table with only restrictive policies shows nothing.
This combination rule is the reason restrictive policies are useful for tenant isolation. Put the tenant boundary in one restrictive policy that applies to every role and command, and put the finer business rules (owner only, manager can see team) in permissive policies. Any new permissive policy someone adds later can widen access within a tenant, but cannot cross the tenant boundary. Without the restrictive layer, a single over-broad permissive policy such as USING (true) for reporting reopens every tenant's data, because it is combined with OR.
The PostgreSQL documentation gives a related example: a restrictive policy that only lets the admin role act when connected over a local socket, by checking that inet_client_addr() is null.
Who bypasses row-level security
This is the section that matters most in incident reviews. The documentation lists three bypass cases.
| Role | Bypasses policies? | How to control it |
|---|---|---|
| Superuser | Always | Never let an application or agent connect as a superuser |
Role with BYPASSRLS | Always | Grant only to backup, migration and break-glass roles; review the list |
| Table owner | Normally yes | ALTER TABLE ... FORCE ROW LEVEL SECURITY subjects the owner to policies |
| Ordinary role with table privileges | No | This is the role your application should use |
The owner bypass is the one that surprises people. Migration tools and frameworks commonly create tables as the same role the application connects with. Every policy then looks correct in code review and does nothing in production, because the connecting role owns the table. Tests written as the same role pass for the same reason.
The fix is structural. Create tables with a dedicated owner role that the application never uses at runtime, grant the application role only the table privileges it needs, and set FORCE ROW LEVEL SECURITY on tenant tables so even owner sessions are filtered. Then test policies by connecting as the application role, not as the migration role.
Roles with BYPASSRLS are non-human identities with tenant-wide reach. Backup jobs, logical replication users, data warehouse loaders and support tooling often get the attribute because it is the easiest way to make them work. Each one should have an owner, a reason and a credential stored in a secrets manager. The Database Credential and Access Security Guide covers how to manage those credentials.
The row_security setting and backups
The documentation warns that it could be disastrous if row security silently omitted rows from a backup. Setting row_security to off does not bypass policies; it makes any query that would be filtered by a policy raise an error instead. Backup tooling uses this so that a backup role lacking bypass rights fails loudly rather than producing a partial dump. The practical rule: give the backup identity BYPASSRLS deliberately, and treat a backup that errors on row security as a configuration fault, not a reason to grant superuser.
Building a multi-tenant model
The tenant model most teams want is: every tenant-scoped table carries a tenant identifier, the application tells the database which tenant the request is for, and policies restrict every command to that tenant. A workable pattern, labelled here as an NHI Mgmt Group recommendation rather than a PostgreSQL rule, is:
- Add a non-null
tenant_idcolumn to every tenant-scoped table and index it, because the policy predicate runs on every query. - Set the tenant per transaction. The application sets a custom configuration value at the start of each transaction (for example with
SET LOCALorset_config(..., true)), and policies read it withcurrent_setting(). Transaction scope matters with connection pools: a session-level setting can carry one tenant's context into the next request on the same connection. - Write one restrictive tenant policy per table covering
ALLcommands, with bothUSINGandWITH CHECKcomparingtenant_idto the current setting. - Add permissive policies for in-tenant rules such as row ownership.
- Force row security on every tenant table and confirm the application role is neither owner, superuser nor
BYPASSRLS. - Fail closed when the setting is missing. Write the predicate so a missing or empty tenant value matches no rows.
Remember that a configuration value set by the application is only as trustworthy as the application. If an attacker can run arbitrary SQL as the application role, they can set the tenant value themselves. Row-level security limits the damage from application bugs that forget a WHERE clause; it does not replace authorisation in the application or protection against SQL injection. The Multi-Tenant SaaS Authorisation and Tenant Isolation Guide covers the application side.
Keep policies simple. The documentation notes that policies which only look at the current row's values are the simplest and best-performing case. Policies that consult other tables through sub-selects or functions are slower and can introduce the race conditions described below.
Leaks and side channels
Constraints and referential integrity
Unique, primary key and foreign key checks always bypass row security so that data integrity holds. That creates covert channels. A user who tries to insert a row with a duplicate key learns that the key exists in a row they cannot see. The documentation suggests designing policies that block such inserts and using surrogate keys rather than meaningful values. In multi-tenant tables, include tenant_id in unique constraints so a uniqueness check only reveals information inside the tenant.
Views
Policies on tables referenced by a view are evaluated with the view owner's rights and the policies that apply to the view owner, unless the view is created with the security_invoker option. A view owned by a role that bypasses row-level security exposes every row to anyone who can query the view. Create views with security_invoker = true on tenant data, or grant them only to roles that should see everything.
Leakproof functions and security definer functions
Functions marked LEAKPROOF may run before policy checks. Only mark a function leakproof if it cannot reveal its arguments through errors or timing. Security definer functions run with their owner's rights and can read past policies; set a fixed search_path and keep them out of schemas exposed to untrusted callers.
Race conditions
Policies that look up other rows can leak during concurrent changes. The documentation's example shows a READ COMMITTED session still seeing data after a user's privilege level was reduced, because the policy sub-select used a snapshot from the start of the query. Mitigations it lists include SELECT ... FOR SHARE in the sub-select, locking the referenced table during infrequent changes, or waiting for concurrent transactions to finish before relying on the new state.
Row-level security on Supabase
Supabase exposes PostgreSQL tables through an HTTP API, which is why row-level security is so widely searched. Supabase's own row-level security documentation says to enable RLS on every table in an exposed schema; a table without it is readable and writable by any role with a grant on it. Once enabled, no data is reachable through the API with a publishable key until you create policies.
- Requests from signed-out users run as the
anonrole and signed-in requests asauthenticated. Use theTOclause to target them. auth.uid()returns the requesting user's ID and returns null when unauthenticated, so Supabase recommends an explicitauth.uid() IS NOT NULLcheck.- Authorisation data belongs in
raw_app_meta_data, which users cannot change, not inraw_user_meta_data, which they can. JWT claims can be stale until the token refreshes. - Secret keys act through the
service_rolerole, which has the bypass attribute. Treat these keys as tenant-wide credentials and keep them out of browsers and mobile apps. - Supabase notes that views bypass RLS by default because they are usually created by the
postgresuser, and recommendssecurity_invoker = trueon Postgres 15 and later. - For performance, index every column a policy filters on and wrap helper calls in a
selectso the optimiser can cache the result per statement.
For key handling, see the Supabase Keys Security Guide.
Testing and monitoring policies
Row-level security fails quietly: a missing policy or a bypassing role returns rows, not errors. Build tests and checks that look for that.
- Catalogue check. Query
pg_classforrelrowsecurityandrelforcerowsecurityon every tenant table, andpg_policiesfor the policies on each. Alert on any tenant table where either flag is false. - Role check. List roles with
rolsuperorrolbypassrlsfrompg_roles, and the owner of each tenant table. The application role should appear in none of these lists. - Cross-tenant tests. In CI, connect as the application role, set tenant A, and attempt to read, update, delete and insert tenant B rows. Every attempt must return zero rows or an error.
- View check. List views over tenant tables and confirm each uses
security_invokeror is restricted to privileged roles. - Audit. Log DDL so that
DISABLE ROW LEVEL SECURITY,DROP POLICYandALTER ROLE ... BYPASSRLSgenerate alerts. The Database Audit Log Detection Guide covers detection rules.
Common failure patterns
- Policies written but row security never enabled on the table, so the policies do nothing.
- The application connects as the table owner without
FORCE ROW LEVEL SECURITY, so every policy is bypassed. - Superuser or
BYPASSRLSon the application role, often added to fix a migration or backup error. USINGwithout a matching write check on customINSERTorUPDATEpolicies, letting a user write a row into another tenant.- A broad permissive policy for reporting that is combined with
ORand opens every tenant. - Session-level tenant settings with pooled connections, leaking one tenant's context into another request.
- Views owned by a privileged role without
security_invoker. - Service role or bypass keys in client code on platforms that expose PostgreSQL over HTTP.
- Tests run as the migration role, which bypasses policies and so always passes.
Practitioner checklist
- Enable and force row-level security on every tenant-scoped table.
- Separate the table owner role from the runtime application role.
- Confirm the application role is not superuser, not
BYPASSRLSand not a table owner. - Keep an owned, reviewed list of every
BYPASSRLSrole and its purpose. - Use one restrictive tenant policy per table with both
USINGandWITH CHECK. - Set tenant context per transaction, and fail closed when it is missing.
- Include
tenant_idin unique constraints and index it. - Create views over tenant data with
security_invoker = true. - Run cross-tenant read and write tests as the application role in CI.
- Alert on
DISABLE ROW LEVEL SECURITY,DROP POLICYand newBYPASSRLSgrants.
Standards and references
- PostgreSQL Documentation: Row Security Policies
- PostgreSQL Documentation: CREATE POLICY
- Supabase Documentation: Row Level Security
- NIST: SP 800-53 Rev. 5 (AC-3 Access Enforcement, AC-6 Least Privilege)
- CIS: Critical Security Controls v8.1
- OWASP: API Security Top 10 2023
Related NHI Mgmt Group resources: PostgreSQL Security Guide · Dynamic Data Masking vs Row-Level Security · Multi-Tenant SaaS Authorisation and Tenant Isolation Guide · Supabase Security