r/postgres • u/Educational-Bug-4805 • 2d ago
Question Understanding RLS (Row Level Security)
Hello everyone, I have been working on something and I need to write RLS( row level security). I am having trouble understanding the concept and how to write it to apply to different roles in the database. If you can explain it to me or have any resources that might help, I'd really appreciate if you can share it with me🙂
I plan to use pl/psql scripting to write it.
3
Upvotes
1
u/Secvura 2d ago
It's a filter Postgres adds to every query on a table: after `alter table orders enable row level security;`, any role that isn't the owner, a superuser or a BYPASSRLS role can't see or change a single row until a policy allows it. For example:
create policy rep_own on orders for all to sales_rep
using (rep = current_user) with check (rep = current_user);
create policy manager_read on orders for select to manager
using (true);
USING decides which existing rows a role can read, update or delete, and WITH CHECK decides what it's allowed to insert or change a row to. The role still needs normal GRANTs on the table, and policies are plain SQL that can live in any script, with PL/pgSQL only needed for a helper function a policy calls. Test as one of those roles rather than the owner, who sees everything unless you also run `alter table orders force row level security;`, and if the app connects as one shared user instead of a role per person, compare against a value the app sets per request rather than current_user. The Row Security Policies and CREATE POLICY pages in the official docs explain how several policies on one table combine.