Join our Newsletter — 33% off our NHI Course
Home› Guides› PostgreSQL Row-Level Security Guide: Policies, Bypass Roles and…
Guide Data Security

PostgreSQL Row-Level Security Guide: Policies, Bypass Roles and Multi-Tenant Pitfalls

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 14 min read
On this page

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 SECURITY runs 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 BYPASSRLS always bypass, and table owners normally bypass unless you set FORCE 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 USING and WITH CHECK. USING filters which rows a command can see; WITH CHECK controls 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.

  • USING decides which existing rows the command can see or act on. Rows that fail are filtered out silently.
  • WITH CHECK decides 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.

CommandExpressions allowedWhat they do
SELECTUSING onlyFilters visible rows
INSERTWITH CHECK onlyChecks each new row; a failing row aborts the command
UPDATEUSING and WITH CHECKFilters rows to update, then checks the new row values
DELETEUSING onlyFilters rows that can be deleted
ALLBothApplies 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.

RoleBypasses policies?How to control it
SuperuserAlwaysNever let an application or agent connect as a superuser
Role with BYPASSRLSAlwaysGrant only to backup, migration and break-glass roles; review the list
Table ownerNormally yesALTER TABLE ... FORCE ROW LEVEL SECURITY subjects the owner to policies
Ordinary role with table privilegesNoThis 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:

  1. Add a non-null tenant_id column to every tenant-scoped table and index it, because the policy predicate runs on every query.
  2. Set the tenant per transaction. The application sets a custom configuration value at the start of each transaction (for example with SET LOCAL or set_config(..., true)), and policies read it with current_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.
  3. Write one restrictive tenant policy per table covering ALL commands, with both USING and WITH CHECK comparing tenant_id to the current setting.
  4. Add permissive policies for in-tenant rules such as row ownership.
  5. Force row security on every tenant table and confirm the application role is neither owner, superuser nor BYPASSRLS.
  6. 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 anon role and signed-in requests as authenticated. Use the TO clause to target them.
  • auth.uid() returns the requesting user's ID and returns null when unauthenticated, so Supabase recommends an explicit auth.uid() IS NOT NULL check.
  • Authorisation data belongs in raw_app_meta_data, which users cannot change, not in raw_user_meta_data, which they can. JWT claims can be stale until the token refreshes.
  • Secret keys act through the service_role role, 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 postgres user, and recommends security_invoker = true on Postgres 15 and later.
  • For performance, index every column a policy filters on and wrap helper calls in a select so 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_class for relrowsecurity and relforcerowsecurity on every tenant table, and pg_policies for the policies on each. Alert on any tenant table where either flag is false.
  • Role check. List roles with rolsuper or rolbypassrls from pg_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_invoker or is restricted to privileged roles.
  • Audit. Log DDL so that DISABLE ROW LEVEL SECURITY, DROP POLICY and ALTER ROLE ... BYPASSRLS generate 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 BYPASSRLS on the application role, often added to fix a migration or backup error.
  • USING without a matching write check on custom INSERT or UPDATE policies, letting a user write a row into another tenant.
  • A broad permissive policy for reporting that is combined with OR and 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 BYPASSRLS and not a table owner.
  • Keep an owned, reviewed list of every BYPASSRLS role and its purpose.
  • Use one restrictive tenant policy per table with both USING and WITH CHECK.
  • Set tenant context per transaction, and fail closed when it is missing.
  • Include tenant_id in 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 POLICY and new BYPASSRLS grants.

Standards and references

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.