How PostgreSQL RLS policies combine
See how PostgreSQL combines RLS policies: permissive rules widen access with OR, restrictive rules narrow it with AND, and both affect SELECT and UPDATE differently.
PostgreSQL row security is easier to use once you stop asking whether a policy “wins” on its own. A command can be covered by more than one policy, and the database combines the ones that apply. The useful question is how those policies interact when one of them should admit tenant-owned rows and another should enforce a rule that no row may violate.
This article focuses on that composition rule. It uses a small table example with one permissive policy and one restrictive policy, then shows how the same row can be selectable, blocked, or writable depending on which side of the check it reaches. The goal is not to reproduce every detail of PostgreSQL’s security model, but to make the boolean behavior obvious enough that you can design your own policies without guessing which one takes precedence.
What this composition rule needs to solve
Row-level security gets much easier to reason about once you stop treating every policy as if it were a standalone gate. PostgreSQL does not evaluate a table’s applicable policies one by one and stop at the first match. Instead, it gathers the policies that apply to the command and the role, then combines them according to policy type.
That distinction matters when a table needs one rule for ordinary tenant access and another rule that no one may violate. A permissive policy can widen the set of rows that are reachable. A restrictive policy can narrow that set further. The useful question is not just “can I write a policy that permits this row?” but “how do I compose a baseline access rule with an invariant that always has to hold?”
The answer is visible in PostgreSQL’s own docs: permissive policies combine with OR, restrictive policies combine with AND, and a mix only works when at least one permissive policy grants access before restrictive policies can narrow it. That means the composition itself is part of the design, not a side effect of the SQL syntax.
export const proofBoundary =
'This module models the documented Boolean composition of applicable RLS policies. It does not execute PostgreSQL, prove privileges, SQL parsing, triggers, or a live database policy decision.';
export function createExamplePolicies() {
return [
{
name: 'tenant_access',
mode: 'PERMISSIVE',
command: 'ALL',
using: (row, actor) => row.tenantId === actor.tenantId,
check: (row, actor) => row.tenantId === actor.tenantId,
},
{
name: 'active_records_only',
mode: 'RESTRICTIVE',
command: 'ALL',
using: (row) => row.active === true,
check: (row) => row.active === true,
},
];
}
export function exampleRows() {
return [
{ id: 1, tenantId: 'acme', active: true, title: 'Acme public record' },
{ id: 2, tenantId: 'acme', active: false, title: 'Acme archived record' },
{ id: 3, tenantId: 'globex', active: true, title: 'Globex public record' },
];
}
function policiesFor(command, policies) {
const normalizedCommand = command.toUpperCase();
if (!['SELECT', 'UPDATE'].includes(normalizedCommand)) {
throw new RangeError(`This example supports SELECT or UPDATE, not ${command}`);
}
return policies.filter(
(policy) => policy.command === 'ALL' || policy.command === normalizedCommand,
);
}
function expressionPasses(policy, phase, row, actor) {
const expression = phase === 'existing'
? policy.using
: (policy.check ?? policy.using);
return expression(row, actor) === true;
}
/**
* Applies PostgreSQL's same-command composition rule:
* (permissive_1 OR permissive_2 OR ...) AND restrictive_1 AND restrictive_2 ...
*/
export function rowAllowed({ command, phase = 'existing', row, actor, policies }) {
if (!row || !actor || !Array.isArray(policies)) {
throw new TypeError('row, actor, and policies are required');
}
if (!['existing', 'proposed'].includes(phase)) {
throw new RangeError(`Unknown policy phase: ${phase}`);
}
const applicable = policiesFor(command, policies);
const permissive = applicable.filter((policy) => policy.mode === 'PERMISSIVE');
const restrictive = applicable.filter((policy) => policy.mode === 'RESTRICTIVE');
// PostgreSQL default-denies when there is no applicable permissive policy.
return (
permissive.some((policy) => expressionPasses(policy, phase, row, actor)) &&
restrictive.every((policy) => expressionPasses(policy, phase, row, actor))
);
}
export function selectRows({ rows, actor, policies }) {
return rows.filter((row) =>
rowAllowed({ command: 'SELECT', phase: 'existing', row, actor, policies }),
);
}
export function updateRow({ rows, id, changes, actor, policies }) {
const index = rows.findIndex((row) => row.id === id);
if (index === -1) return { status: 'not-found', rows: [...rows] };
const existing = rows[index];
if (!rowAllowed({ command: 'UPDATE', phase: 'existing', row: existing, actor, policies })) {
// PostgreSQL ordinarily filters an inaccessible UPDATE target rather than updating it.
return { status: 'not-visible', rows: [...rows] };
}
const proposed = { ...existing, ...changes };
if (!rowAllowed({ command: 'UPDATE', phase: 'proposed', row: proposed, actor, policies })) {
// A failed WITH CHECK is an error in PostgreSQL; this model reports it explicitly.
return { status: 'check-violation', rows: [...rows] };
}
return {
status: 'updated',
rows: rows.map((row, rowIndex) => (rowIndex === index ? proposed : row)),
};
}
export function postgresFixtureSql() {
return `
CREATE TABLE tenant_records (
id integer PRIMARY KEY,
tenant_id text NOT NULL,
active boolean NOT NULL,
title text NOT NULL
);
ALTER TABLE tenant_records ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_access ON tenant_records
AS PERMISSIVE FOR ALL TO app_user
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
CREATE POLICY active_records_only ON tenant_records
AS RESTRICTIVE FOR ALL TO app_user
USING (active)
WITH CHECK (active);
`.trim();
}
SourcesPostgreSQL docs: Row Security Policies (opens a new tab)PostgreSQL docs: CREATE POLICY (opens a new tab)
The minimal example keeps the contract small
The fixture models a table of tenant-owned records with one row that should be visible to the current tenant and active rows only. The permissive policy answers the tenant question: is this row from the caller’s tenant? The restrictive policy answers the non-negotiable question: is this row active?
That is the smallest useful shape for the composition rule. If the row belongs to the tenant but is inactive, the permissive policy alone is not enough. If the row is active but belongs to another tenant, the restrictive policy alone is not enough. The row must satisfy both parts of the final expression to be selectable or updatable.
In the article’s example, the logic is expressed as a pair of policies on the same table: a permissive tenant-access rule and a restrictive active-record rule. The sample does not pretend to be a full application schema; it is deliberately narrower, because the point is to make the boolean composition visible rather than to model authentication, tenancy, or auditing in one go.
Why permissive policies act like an OR list
PostgreSQL’s permissive policies are the default. When more than one permissive policy applies to a command, the result is the union of those policies: if any applicable permissive policy allows the row, the row is still in play. That makes permissive policies useful for additive access rules, such as “the row belongs to the tenant” or “the caller has one of several roles that may see it.”
This behavior is easy to miss if you come from a “single policy per concern” mental model. Two permissive policies do not compete with each other; they expand the set of rows that can survive the policy phase. The docs compare that behavior to role membership, which is a helpful intuition because both systems accumulate rights rather than subtracting them one by one.
In practice, that means a permissive tenant rule can define the baseline set of rows that a request may consider. If no permissive policy grants access, PostgreSQL default-denies the table. That default-deny behavior is what keeps row security safe by default, but it also means that a restrictive rule cannot rescue a table on its own.
SourcesPostgreSQL docs: Row Security Policies (opens a new tab)PostgreSQL docs: CREATE POLICY (opens a new tab)
Why restrictive policies are an AND list
Restrictive policies exist for the cases where “allowed unless forbidden” is too weak. PostgreSQL combines every applicable restrictive policy with AND, which means every restrictive condition must pass for the row to remain accessible. A restrictive policy does not add rows to the candidate set; it reduces the rows that the permissive policies have already admitted.
That makes restrictive policies a good fit for non-negotiable invariants. In the example, the row must be active. You could imagine other restrictive conditions such as “must be visible in the current region,” “must not be soft-deleted,” or “must satisfy a compliance flag.” The key point is that these constraints should narrow access without needing to duplicate the tenant rule in every policy.
The docs also warn that restrictive policies cannot stand alone in a meaningful access design. If no permissive policy grants access, the AND chain never gets a chance to narrow anything, because the overall result is already deny. That is exactly why composition matters: permissive policies establish the allowed universe, and restrictive policies constrain it.
SELECT and UPDATE do not use the same check path
The example keeps SELECT and UPDATE in the same discussion because PostgreSQL treats the existing row and the proposed row differently. USING decides which existing rows a command may see or target. WITH CHECK decides whether the row being written is allowed to enter the table. Those are related, but they are not interchangeable.
That distinction becomes important when a tenant can edit its own row but must not make the row inactive or move it into another tenant. The existing row must pass the selection side of the policy, and the proposed row must pass the write side. In the supplied model, the same boolean shape is used for both because the example is intentionally small, but the article explains why the engine still evaluates them as two phases.
This is also where command type matters. A policy written for ALL can affect both the read side and the write side, while a policy written for SELECT only affects visibility. The article’s example keeps the SQL compact by using one table and two policies, but the explanation makes clear that PostgreSQL’s composition rule applies per command and per phase, not just once per table.
The write check also sees changes made by a BEFORE ROW trigger. If a normalization trigger rewrites a proposed tenant identifier or activity flag, evaluate the resulting row when you reason about WITH CHECK. A useful database test is to run the same update as the intended application role, inspect the values the trigger would produce, and check that the combined write policies reject a result that violates the invariant.
SourcesPostgreSQL docs: CREATE POLICY (opens a new tab)PostgreSQL docs: Row Security Policies (opens a new tab)
What the sample fixture proves
The provided example code is not a live PostgreSQL session; it is an application-owned model of the documented boolean composition rule. That proof boundary is important. The module proves the logic that the article teaches: a row is allowed only when at least one applicable permissive policy passes and every applicable restrictive policy passes.
That boundary is narrow on purpose. The example does not claim to emulate PostgreSQL parsing, planner rewrites, ownership bypass, leakproof functions, referential-integrity exceptions, or concurrent transaction behavior. Those are real parts of PostgreSQL’s security model, but they are not needed to answer the policy-composition question. The article keeps them in the limits section rather than pretending a few JavaScript functions are a database.
The regression tests are useful because they make the policy algebra observable. A row from the right tenant but marked inactive remains hidden. A proposed update that would deactivate the row fails the write-side check. An update against another tenant’s row never gets past the visibility gate. Those are exactly the outcomes the reader needs to predict before they write their own policies.
SourcesPostgreSQL docs: CREATE POLICY (opens a new tab)PostgreSQL docs: Row Security Policies (opens a new tab)
Limits and design choices
The most important limit is that policy composition answers access questions, not business-process questions. A restrictive policy is a good fit for a universal invariant such as “active only,” but it is not a substitute for application validation, audit trails, or a workflow that must remember who approved a change. If your rule is really about state transitions rather than row access, row security alone is the wrong abstraction.
A second limit is that multiple policies can make intent harder to read if they are not named carefully. A single broad policy may be easier to understand when the rule is simple. Separate permissive and restrictive policies become more valuable when you need to reason about composition, share a table across several roles, or keep a permanent invariant visible beside a tenant-specific rule.
A third limit is that the example intentionally avoids cross-table policy checks. PostgreSQL supports them, but the documentation warns about race conditions and other subtle effects when policy expressions consult other rows or tables. For this article, the useful lesson is the composition rule itself: permissive policies create the candidate set, restrictive policies narrow it, and both need to be designed together.
SourcesPostgreSQL docs: CREATE POLICY (opens a new tab)PostgreSQL docs: Row Security Policies (opens a new tab)
The decision rule to carry forward
If you only need one sentence to remember, make it this: use permissive policies for the rows you want to admit, and use restrictive policies for the rows you must never admit unless every guard passes. In PostgreSQL, the final answer is not the individual policy names. It is the boolean shape formed by OR across permissive policies and AND across restrictive policies.
That rule is why the tenant-access example stays readable. The tenant rule says which rows belong in the candidate set. The active-record rule says which of those candidates are still acceptable. Together they answer the question the database actually enforces: may this row be selected or written for this command and this role?
Once you think in that order, policy design gets less mysterious. Start by identifying the rows that should be reachable at all. Then add the invariant conditions that should further reduce that set. If you cannot explain which policy widens access and which policy narrows it, the design is probably still mixing concerns that should stay separate.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createExamplePolicies,
exampleRows,
rowAllowed,
selectRows,
updateRow,
} from './main.mjs';
test('SELECT returns an actor tenant row only when both permissive and restrictive policies pass', () => {
const rows = exampleRows();
const policies = createExamplePolicies();
const actor = { tenantId: 'acme' };
const visible = selectRows({ rows, actor, policies });
assert.deepEqual(visible.map((row) => row.id), [1]);
});
test('SELECT filters an inactive row even though the permissive tenant policy passes', () => {
const policies = createExamplePolicies();
const actor = { tenantId: 'acme' };
const inactiveAcmeRow = {
id: 20,
tenantId: 'acme',
active: false,
title: 'Archived',
};
assert.equal(
rowAllowed({
command: 'SELECT',
phase: 'existing',
row: inactiveAcmeRow,
actor,
policies,
}),
false,
);
});
test('UPDATE rejects a proposed change that violates the restrictive WITH CHECK rule', () => {
const rows = exampleRows();
const policies = createExamplePolicies();
const actor = { tenantId: 'acme' };
const result = updateRow({
rows,
id: 1,
changes: { active: false },
actor,
policies,
});
assert.equal(result.status, 'check-violation');
assert.equal(result.rows.find((row) => row.id === 1).active, true);
});
test('UPDATE cannot target another tenant row before proposed-row checks run', () => {
const rows = exampleRows();
const policies = createExamplePolicies();
const actor = { tenantId: 'acme' };
const result = updateRow({
rows,
id: 3,
changes: { title: 'Attempted cross-tenant edit' },
actor,
policies,
});
assert.equal(result.status, 'not-visible');
assert.equal(result.rows.find((row) => row.id === 3).title, 'Globex public record');
});
SourcesPostgreSQL docs: CREATE POLICY (opens a new tab)PostgreSQL docs: Row Security Policies (opens a new tab)


