Row-Level Security Policies
Filter rows per user automatically.
What Is Row-Level Security?
Row-Level Security (RLS) is a PostgreSQL feature that lets you control which rows of a table a given database user or role can see or modify. Instead of filtering rows in every query, you define a policy once and PostgreSQL enforces it automatically on every SELECT, INSERT, UPDATE, and DELETE.
Think of it as an invisible WHERE clause that is attached to the table itself rather than to any specific query.
Enabling RLS on a Table
RLS is disabled by default. You must explicitly turn it on for each table using ALTER TABLE ... ENABLE ROW LEVEL SECURITY. Once enabled, any role that is not the table owner will see zero rows until at least one policy is created.
-- Create a sample table
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
owner TEXT NOT NULL,
amount NUMERIC(10,2)
);
-- Enable RLS
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;All lessons in this course
- Roles and Privileges
- Row-Level Security Policies
- Column-Level Permissions
- Auditing Access