How to enable row-level security (RLS) in PostgreSQL
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Row-level security (RLS) is a feature in PostgreSQL that allows you to define policies to restrict access to individual rows in a table. This ensures that users can only access or modify data that they’re authorized to see.
First, let’s turn on RLS for a specific table. Here, I’ll assume a table named employees.
ALTER TABLE employees ENABLE ROW LEVEL SECURITY;
By default, this will block all access to the table unless a policy is applied. To still allow the table owner access, you can use:
ALTER TABLE employees FORCE ROW LEVEL SECURITY;
A policy dictates what data can be accessed by whom. Let’s create a policy to allow users to see only the rows where the department matches their role.
CREATE POLICY employee_policy
ON employees
FOR SELECT
USING (department = current_setting('my_app.user_role'));
After creating a policy, apply it to the table using ALTER TABLE.
ALTER TABLE employees FORCE ROW LEVEL SECURITY;
ALTER TABLE employees ALTER POLICY employee_policy USING (department = current_setting('my_app.user_role'));
You can test whether RLS is working by changing the current setting for the role and trying a SELECT query.
SET my_app.user_role = 'Engineering';
SELECT * FROM employees;
You can use session variables to make the policies dynamic.
ALTER TABLE employees ALTER POLICY employee_policy USING (department = current_setting('my_app.user_role'));
Then, whenever a user logs in, set the session variable to their role.
SET my_app.user_role = '<user-role>';
RLS is best for multi-tenant applications or applications with different user roles that require access to subsets of data. It’s not recommended for systems with extremely high throughput because it might add performance overhead.
For access management workflows, Basedash complements SQL controls with governed reporting, shared visibility, and AI-assisted analysis so teams can monitor permission changes without losing auditability.
If RLS doesn’t fit your needs, consider using other PostgreSQL features like Views or Table Partitioning for achieving similar results.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.