AI Hints
Home›PostgreSQL Tutorial›Roles, Privileges and Row-Level Security
PostgreSQL · Lesson 80 of 120

Row-Level Security

Each sees their own rows.

⏱ 2 min read▶ Video at 1:11:54🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Riverside has two shops, in Toronto and in Dublin. Each manager should only see their own shop's orders, from the same table. Row level security adds a hidden where clause for each user.

  • Two shops
  • Same table
  • Own rows only

A policy per shop

We add a shop column. Enable row level security switches it on. The policy says, you see rows where shop equals your role name. Then we switch to the dublin role. Run it. Dublin sees only Dublin orders.

query.sqlsql
CREATE TABLE shop_orders (id int, shop text, total numeric);
INSERT INTO shop_orders VALUES (1, 'toronto', 40), (2, 'dublin', 25), (3, 'dublin', 60);

ALTER TABLE shop_orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_shop ON shop_orders USING (shop = current_user);

CREATE ROLE dublin;
GRANT SELECT ON shop_orders TO dublin;
SET ROLE dublin;
SELECT * FROM shop_orders;
Output
CREATE TABLE
INSERT 0 3
ALTER TABLE
CREATE POLICY
CREATE ROLE
GRANT
SET
 id |  shop  | total
----+--------+-------
  2 | dublin |    25
  3 | dublin |    60
(2 rows)

RLS notes

Table owners and superusers skip policies, unless you force them. Using filters reads, and with check controls writes. Policies can use settings, like the current tenant ID. And always test as the real role.

keyvalue
Ownersbypass unless FORCE
USINGfilters reads
WITH CHECKguards writes
Testas the real role

Summary

Row level security adds policies, so each user sees only their own rows. Next, practise with staff access rules.

Key takeaways
  • ENABLE RLS
  • CREATE POLICY
  • current_user
Next up: Practice: Shop Staff Access — tenants and settings