PostgreSQL
Beginner
1 min read
Roles, Permissions, and Security
Example
-- Create roles
CREATE ROLE app_user LOGIN PASSWORD 'securepassword';
CREATE ROLE app_admin LOGIN PASSWORD 'adminpassword';
CREATE ROLE readonly;
-- Grant privileges
GRANT CONNECT ON DATABASE myappdb TO app_user;
GRANT USAGE ON SCHEMA shop TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA shop TO app_user;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO readonly;
-- Make app_admin a member of app_user (inherits privileges)
GRANT app_user TO app_admin;
-- Row-Level Security example — users only see their own orders
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY orders_isolation_policy ON orders
FOR ALL
USING (user_id = current_setting('app.current_user_id')::INTEGER);
-- Set the current user context in application code
SET LOCAL app.current_user_id = '42';
-- Revoke default public schema access (security best practice)
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE myappdb FROM PUBLIC;
Related Resources
PostgreSQL Reference
Complete tag & property list
PostgreSQL How-To Guides
Step-by-step practical guides
PostgreSQL Exercises
Practice what you've learned
More in PostgreSQL