sqladvanced
Row-Level Security Policies
Enforce data access rules at the database level with PostgreSQL Row-Level Security policies.
sqlPress ⌘/Ctrl + Shift + C to copy
-- Enable RLS on the table
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
-- Policy: Users can only see their own documents
CREATE POLICY select_own_docs ON documents
FOR SELECT
USING (user_id = current_setting('app.user_id')::uuid);
-- Policy: Users can insert only for themselves
CREATE POLICY insert_own_docs ON documents
FOR INSERT
WITH CHECK (user_id = current_setting('app.user_id')::uuid);
-- Policy: Admins can see everything
CREATE POLICY admin_all_docs ON documents
FOR ALL
USING (current_setting('app.role') = 'admin');
-- Set user context before queries
SET app.user_id = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
SET app.role = 'user';Sponsored
Try Supabase — Postgres with Built-in RLS
Use Cases
- Multi-tenant databases
- User data isolation
- HIPAA compliance
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqladvanced
Table Partitioning by Range
Partition large tables by date range for faster queries and easier data lifecycle management.
Best for: Time-series data
#partitioning#performance
sqlintermediate
Deferred Foreign Key Constraints
Defer constraint checking to transaction commit for circular references and batch operations.
Best for: Circular references
#constraints#transactions
sqlintermediate
JSONB Query and Indexing Patterns
Query, filter, and index JSONB columns in PostgreSQL for flexible document-style data storage.
Best for: Flexible metadata storage
#jsonb#postgres
sqlbeginner
INSERT ... RETURNING for Immediate Results
Use RETURNING clause to get inserted rows immediately without a separate SELECT query.
Best for: getting generated IDs
#sql#insert