Getting the "permission denied for table table_name" error in SQL? This guide explains what causes this error and how to fix it with practical examples.
What Causes This Error?
The permission denied error (42501) occurs when:
- User lacks SELECT/INSERT/UPDATE/DELETE privilege
- Trying to access schema user can't see
- Row-level security blocking access
- Role not granted required permissions
How to Fix It
- Grant necessary permissions: GRANT SELECT, INSERT ON table TO user.
- Check current grants: \dp table_name in psql.
- Verify schema access: GRANT USAGE ON SCHEMA schema_name TO user.
- Review RLS policies if enabled.
Example: Wrong vs Correct
❌ Code That Causes the Error
-- As unprivileged user: SELECT * FROM admin.sensitive_data; -- Error: permission denied for schema admin
✅ Corrected Code
-- As superuser, grant access: GRANT USAGE ON SCHEMA admin TO app_user; GRANT SELECT ON admin.sensitive_data TO app_user;
Quick Checklist
- [ ] Verify column/table names are spelled correctly
- [ ] Check data types match expected values
- [ ] Review query syntax for missing keywords
- [ ] Ensure referenced tables/columns exist
Related SQL Errors
If you're troubleshooting SQL errors, you might also encounter: