RLS Simplified
Last edited: 2/21/2025
Basic summary
Row-Level Security (RLS) Policy: A WHERE or CHECK condition applied automatically to database queries
Key features:
- Applies without being explicitly added to each query, which makes it good for policing row access from unknown entities, such as those leveraging the anon or authenticated roles.
- Can be set for specific actions (e.g., SELECT, INSERT)
- Can target particular database roles (e.g., "anon", "authenticated")
Contrast with regular conditions:
- Regular conditions: Apply to all roles and must be added manually to each query
- RLS policies: Applied automatically to specified actions and roles
Hands on walk-through for conditions
USING:
The USING keyword inspects the value of row to see if it should be made visible to the query.
When you SELECT, UPDATE, or DELETE, you have to use a WHERE statement to search for specific rows:
1-- select2select *3from some_table4where id = 5;56-- update7update some_table8set id = 69where id = 5;1011-- delete12delete from some_table13where id = 6;Even when you don't use a WHERE statement, there's still an implicit one:
1-- ...your query2WHERE true;The USING clause appends more to the WHERE statement:
1-- Your Using condition2USING (3 (select auth.uid()) = user_id4);56-- Your query without RLS:7SELECT * FROM some_table8WHERE id = 5 OR id = 6;910-- Your query after RLS11SELECT * FROM some_table12WHERE13 (id = 5 OR id = 6)14 AND15 (select auth.uid()) = user_id) -- <--- added by the USING clause;WITH CHECK:
Let's say you have a profile table. Well, you don't want user's to be able to modify their user_id when they make an insert, do you?
The WITH CHECK condition inspects values that are being added or modified. For INSERT you'd use it by itself. There's no need for a using clause:
1-- Allow users to add to table, but make sure their user_id matches the one in their JWT:23create policy "Allow user to add posts"4on "public"."posts"5as PERMISSIVE6for INSERT7to authenticated8with check(9 (select auth.uid()) = user_id10);1112-- Example: failing insert13INSERT INTO posts14VALUES (<false id>, <comment>);1516-- Example: successful insert17INSERT INTO posts18VALUES (<real id>, <comment>);INSERTs do not rely on WHERE clauses, but they can have constraints. In this case, the RLS acts as a CHECK constraint against a column, e.g.:
1ALTER TABLE table_name2ADD CONSTRAINT constraint_name CHECK (condition);What distinguishes it from normal CHECK constraints is that it is only activate for certain roles or methods.
UPDATEs:
UPDATE both filters for rows to change and then adds new values to the table, so it requires both USING and WITH CHECK conditions:
1create policy "Allow user to edit their stuff"2on "public"."<SOME TABLE NAME>"3as RESTRICTIVE4for UPDATE5to authenticated6using (7 (select auth.uid()) = user_id8)9with check(10 (select auth.uid()) = user_id11);