SQL · Module 14 · Lesson 32 min read

Row Level Security (RLS)

What is RLS?

Policies attached to a table that decide which rows each user can see and change. The database adds the policy condition to every query automatically — the app can't forget it.

Turning it on

CSS
ALTER TABLE expenses ENABLE ROW LEVEL SECURITY;

⚠️ Once enabled with no policies, normal users see nothing (deny by default) ✅ safe.

Policies

vbnet
CREATE POLICY "Users read own expenses"
ON expenses FOR SELECT
TO authenticated
USING (user_id = auth.uid());
  • FOR – SELECT, INSERT, UPDATE, DELETE or ALL
  • TO – which roles (Supabase: authenticated, anon)
  • USING (…) – which existing rows are visible/affected (SELECT, UPDATE, DELETE)
  • WITH CHECK (…) – which new/changed rows are allowed (INSERT, UPDATE) → stops users inserting rows "for" someone else
  • Several permissive policies are combined with OR

auth.uid() in Supabase

Returns the logged-in user's UUID from their JWT. Store it in an owner column: user_id UUID NOT NULL DEFAULT auth.uid() REFERENCES auth.users(id)

Common policy patterns

  • Own rows only: USING (user_id = auth.uid())
  • Public read, owner write: a SELECT policy USING (true) + write policies using the owner
  • Team/shared access: USING (EXISTS (SELECT 1 FROM members m WHERE m.team_id = t.team_id AND m.user_id = auth.uid()))
  • Role-based: check a claim in auth.jwt() or a profiles.role column

Performance tips

  • Index the columns used in policies (user_id)
  • Wrap the function: user_id = (SELECT auth.uid()) → evaluated once per query instead of per row
  • Keep policy subqueries simple

Important caveats

  • Table owners and superusers bypass RLS (also the service_role key) — test policies as a normal user
  • Views bypass RLS unless created WITH (security_invoker = true)
  • SECURITY DEFINER functions bypass RLS — check access manually inside them
  • Supabase warns you about tables in public without RLS — turn it on for every table

Example

SQL
-- Supabase-style table owned by auth users (UUIDs)
CREATE TABLE notes (
  id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id    UUID NOT NULL DEFAULT auth.uid(),
  body       TEXT NOT NULL,
  is_public  BOOLEAN NOT NULL DEFAULT false
);
CREATE INDEX ON notes (user_id);

ALTER TABLE notes ENABLE ROW LEVEL SECURITY;

-- Owners can do everything with their own notes
CREATE POLICY "own notes - read"   ON notes FOR SELECT TO authenticated
  USING (user_id = (SELECT auth.uid()) OR is_public);
CREATE POLICY "own notes - insert" ON notes FOR INSERT TO authenticated
  WITH CHECK (user_id = (SELECT auth.uid()));
CREATE POLICY "own notes - update" ON notes FOR UPDATE TO authenticated
  USING (user_id = (SELECT auth.uid())) WITH CHECK (user_id = (SELECT auth.uid()));
CREATE POLICY "own notes - delete" ON notes FOR DELETE TO authenticated
  USING (user_id = (SELECT auth.uid()));

GRANT SELECT, INSERT, UPDATE, DELETE ON notes TO authenticated;

-- Seed data as admin (owner bypasses RLS)
INSERT INTO notes (user_id, body, is_public) VALUES
  ('aaaaaaaa-0000-0000-0000-000000000001', 'Asha private: salary plan', false),
  ('aaaaaaaa-0000-0000-0000-000000000001', 'Asha public: budgeting tips', true),
  ('bbbbbbbb-0000-0000-0000-000000000002', 'Ravi private: loan details', false);

-- Simulate a request from Ravi (Supabase sets these from the JWT)
SET ROLE authenticated;
SET request.jwt.claim.sub = 'bbbbbbbb-0000-0000-0000-000000000002';

SELECT body FROM notes ORDER BY id;
-- Asha public: budgeting tips
-- Ravi private: loan details          (Asha's private note is invisible ✅)

UPDATE notes SET body = 'hacked' WHERE body LIKE 'Asha%';   -- UPDATE 0 ✅ (not his rows)

-- Trying to insert a note pretending to be Asha → blocked by WITH CHECK
DO $$ BEGIN
  INSERT INTO notes (user_id, body) VALUES ('aaaaaaaa-0000-0000-0000-000000000001', 'fake');
EXCEPTION WHEN insufficient_privilege THEN
  RAISE NOTICE 'Blocked: %', SQLERRM;    -- new row violates row-level security policy
END $$;

INSERT INTO notes (body) VALUES ('Ravi: new note') RETURNING user_id;   -- defaults to auth.uid() ✅
RESET ROLE;
RESET request.jwt.claim.sub;

-- Which policies exist?
SELECT policyname, cmd, qual, with_check FROM pg_policies WHERE tablename = 'notes';