Row-Level Security

Updated · 9 min read
hardPostgreSQL 18sqlrow-level-securityrlspoliciessecurityinterview

Row-level security (RLS) in SQL is a rule, enforced by the database, that decides which rows of a table each user can see or change. Privileges from Users, Roles and Privileges work on whole tables and columns: a role can read payments or it can't. RLS goes further, so that in a student portal Navika sees only Navika's payments even though every student queries the same table. Because the database applies the rule to every query, a forgotten WHERE in the application can't leak anyone else's data. In this lesson, we will enable RLS on payments, write policies for reading and writing, test them as different users, and look at how other databases do the same job.

In One Minute

  • ALTER TABLE t ENABLE ROW LEVEL SECURITY turns RLS on; then no rows are visible until a policy allows them.
  • CREATE POLICY name ON t FOR SELECT USING (condition) filters the rows a role can read.
  • WITH CHECK (condition) controls which rows a role may insert or update.
  • The table's owner and superusers bypass RLS unless you add FORCE ROW LEVEL SECURITY.
  • Apps that use one database login can pass the user's id with a setting, such as app.student_id.

Syntax

SQL
ALTER TABLE table_name ENABLE ROW LEVEL SECURITY;
 
CREATE POLICY policy_name ON table_name
  [FOR {ALL | SELECT | INSERT | UPDATE | DELETE}]
  [TO role_name]
  [USING (condition)]          -- which existing rows are visible or affected
  [WITH CHECK (condition)];    -- which new or changed rows are allowed

Each Student Sees Their Own Payments

Each student gets a login role, and a small table maps login roles to student ids. The policy shows a payment only to the login that belongs to its student:

SQL▶ Try it
CREATE TABLE student_logins (
  role_name  TEXT PRIMARY KEY,
  student_id INTEGER NOT NULL REFERENCES students (student_id)
);
INSERT INTO student_logins VALUES ('srihitha_login', 101), ('navika_login', 103);
 
CREATE ROLE student_portal NOLOGIN;
GRANT SELECT ON payments, student_logins TO student_portal;
CREATE ROLE srihitha_login LOGIN IN ROLE student_portal;
CREATE ROLE navika_login LOGIN IN ROLE student_portal;
 
ALTER TABLE payments ENABLE ROW LEVEL SECURITY;
 
CREATE POLICY own_payments ON payments
  FOR SELECT
  TO student_portal
  USING (student_id = (SELECT student_id FROM student_logins
                       WHERE role_name = current_user));
 
SET ROLE navika_login;
SELECT payment_id, student_id, amount_usd FROM payments ORDER BY payment_id;
 
SET ROLE srihitha_login;
SELECT count(*) AS visible_payments FROM payments;
 
RESET ROLE;
SELECT count(*) AS all_payments FROM payments;
Output
CREATE TABLE
 
INSERT 0 2
 
CREATE ROLE
 
GRANT
 
CREATE ROLE
 
CREATE ROLE
 
ALTER TABLE
 
CREATE POLICY
 
SET
 
 payment_id | student_id | amount_usd
------------+------------+------------
          6 |        103 |     225.00
          7 |        103 |     225.00
(2 rows)
 
SET
 
 visible_payments
------------------
                5
(1 row)
 
RESET
 
 all_payments
--------------
            7
(1 row)

Explanation: The same SELECT returns different rows for different users. As navika_login, the policy's condition is true only for student 103, so two payments appear. Srihitha sees her five. Neither query mentions a student id: the database adds the condition itself. Back as the original user, the table's owner, all seven payments are visible, because owners bypass RLS.

SELECT * FROM payments returns 2 rows for navika_login, 5 for srihitha_login and 7 for the owner

No Policy Means No Rows

Enabling RLS without a matching policy hides every row, rather than raising an error:

SQL▶ Try it
CREATE ROLE student_portal NOLOGIN;
GRANT SELECT ON payments TO student_portal;
 
ALTER TABLE payments ENABLE ROW LEVEL SECURITY;
 
SET ROLE student_portal;
SELECT count(*) AS visible_payments FROM payments;
RESET ROLE;
Output
CREATE ROLE
 
GRANT
 
ALTER TABLE
 
SET
 
 visible_payments
------------------
                0
(1 row)
 
RESET

Explanation: The role has SELECT, so the query runs, but no policy allows any row, so it sees zero. This "default deny" is safe: forgetting a policy hides data instead of exposing it.

Controlling Writes with WITH CHECK

USING filters rows that already exist; WITH CHECK tests rows being written. A student portal might let students record their own payments, but never one for someone else:

SQL▶ Try it
CREATE TABLE student_logins (role_name TEXT PRIMARY KEY, student_id INTEGER NOT NULL REFERENCES students (student_id));
INSERT INTO student_logins VALUES ('navika_login', 103);
CREATE ROLE navika_login LOGIN;
GRANT SELECT, INSERT ON payments TO navika_login;
GRANT SELECT ON student_logins TO navika_login;
 
ALTER TABLE payments ENABLE ROW LEVEL SECURITY;
 
CREATE POLICY own_payments_all ON payments
  FOR ALL
  TO navika_login
  USING (student_id = (SELECT student_id FROM student_logins WHERE role_name = current_user))
  WITH CHECK (student_id = (SELECT student_id FROM student_logins WHERE role_name = current_user));
 
SET ROLE navika_login;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 10.00, '2026-01-05', '2026-01-05', 'card');
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (101, 4, 10.00, '2026-01-05', '2026-01-05', 'card');
 
SELECT payment_id, student_id, amount_usd FROM payments ORDER BY payment_id;
RESET ROLE;
Output
CREATE TABLE
 
INSERT 0 1
 
CREATE ROLE
 
GRANT
 
GRANT
 
ALTER TABLE
 
CREATE POLICY
 
SET
 
INSERT 0 1
 
ERROR:  new row violates row-level security policy for table "payments"
 
 payment_id | student_id | amount_usd
------------+------------+------------
          6 |        103 |     225.00
          7 |        103 |     225.00
          8 |        103 |      10.00
(3 rows)
 
RESET

Explanation: Navika's own payment passes the WITH CHECK condition and is inserted as payment 8. A payment for Srihitha (101) fails it, and the database refuses with "new row violates row-level security policy". Her SELECT shows her three payments, including the new one.

USING filters the rows a role can see; WITH CHECK rejects new rows that break the rule

One App Login, Many Users

Most web apps connect with a single database role and know the signed-in user only in application code. They can pass the user's id to the database with a setting at the start of each transaction, and policies read it with current_setting:

SQL▶ Try it
CREATE ROLE web_app LOGIN;
GRANT SELECT ON payments TO web_app;
 
ALTER TABLE payments ENABLE ROW LEVEL SECURITY;
 
CREATE POLICY portal_payments ON payments
  FOR SELECT
  TO web_app
  USING (student_id = current_setting('app.student_id')::INTEGER);
 
SET ROLE web_app;
 
SELECT set_config('app.student_id', '103', false);
SELECT payment_id, student_id FROM payments ORDER BY payment_id;
 
SELECT set_config('app.student_id', '102', false);
SELECT count(*) AS visible_payments FROM payments;
 
RESET ROLE;
Output
CREATE ROLE
 
GRANT
 
ALTER TABLE
 
CREATE POLICY
 
SET
 
 set_config
------------
 103
(1 row)
 
 payment_id | student_id
------------+------------
          6 |        103
          7 |        103
(2 rows)
 
 set_config
------------
 102
(1 row)
 
 visible_payments
------------------
                0
(1 row)
 
RESET

Explanation: With app.student_id set to 103, the app sees Navika's two payments; set to 102, it sees none, because Advitha hasn't paid yet. In a real app, the program runs SET LOCAL app.student_id = '...' (or set_config(..., true)) inside each transaction, using the signed-in user's id, so the value never leaks into the next request on a pooled connection.

Row-Level Security in Other Databases

DatabaseHow
PostgreSQLENABLE ROW LEVEL SECURITY and CREATE POLICY
SQL Server (2016+)An inline table-valued function as a predicate, attached with CREATE SECURITY POLICY ... ADD FILTER PREDICATE
OracleVirtual Private Database (VPD) policies, via DBMS_RLS
MySQLNo built-in RLS; use views that filter on the user, plus privileges that allow only the views

Tabs showing each database's version are coming to this course.

Every Query Passes the Policy

Common Mistakes

Testing as the owner. Everything is visible, so the policies seem to "not work". Test with SET ROLE as the real role.

Writing USING but forgetting WITH CHECK on writes. For FOR ALL policies, USING doubles as the check, but separate INSERT policies need WITH CHECK.

Session-wide settings on pooled connections. Use SET LOCAL inside the transaction so one user's id doesn't stay on the connection.

Slow policy conditions. The condition runs for every query; index the columns it uses.

Interview Corner

What is row-level security?

A database feature that filters which rows each user can read or modify, using policies the database adds to every query, independent of the application's own WHERE clauses.

What's the difference between USING and WITH CHECK in a PostgreSQL policy?

USING decides which existing rows are visible or can be updated or deleted. WITH CHECK decides which new or updated rows are allowed to be written.

Who bypasses row-level security in PostgreSQL?

Superusers, roles with BYPASSRLS, and the table's owner, unless the table has FORCE ROW LEVEL SECURITY.

Practice

Challenge (module checkpoint, part 2): Create a login role srihitha_login that can read enrollments, but only Srihitha's (student 101) rows, using a policy. Show what it sees.

Show solution
SQL▶ Try it
CREATE ROLE srihitha_login LOGIN;
GRANT SELECT ON enrollments TO srihitha_login;
 
ALTER TABLE enrollments ENABLE ROW LEVEL SECURITY;
 
CREATE POLICY own_enrollments ON enrollments
  FOR SELECT
  TO srihitha_login
  USING (student_id = 101);
 
SET ROLE srihitha_login;
SELECT student_id, course_id, status FROM enrollments ORDER BY course_id;
RESET ROLE;
Output
CREATE ROLE
 
GRANT
 
ALTER TABLE
 
CREATE POLICY
 
SET
 
 student_id | course_id |  status
------------+-----------+-----------
        101 |         1 | completed
        101 |         2 | completed
        101 |         3 | active
        101 |         4 | active
(4 rows)
 
RESET

The role reads only Srihitha's four enrollments. For many students, use a mapping table or a setting as above, rather than one policy per student. Together with Parameters and Prepared Statements' practice, this completes the module checkpoint.

Quick check: Row-level security

3 questions
1RLS is enabled on a table with no policies. What does a role with SELECT see?
2Which clause rejects inserting a row for another student?
3Why might policies seem to do nothing during testing?

Key Takeaways

You want toWrite
Turn RLS onALTER TABLE payments ENABLE ROW LEVEL SECURITY;
Filter readsCREATE POLICY p ON payments FOR SELECT USING (student_id = ...);
Check writes... WITH CHECK (student_id = ...)
Include the ownerALTER TABLE payments FORCE ROW LEVEL SECURITY;

Was this tutorial helpful?

Lesson 94 of 115