Grant SELECT on all tables
Granting SELECT table by table is slow and misses tables added later. Each engine has a schema- or database-wide form; the per-table script is the fallback.
The task
A new analyst needs read access across a whole schema, and granting table by table takes forever and goes stale with the next migration.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
GRANT SELECT ON ALL TABLES IN SCHEMA public TO analyst;
-- plus usage of the schema itself, or the grant above is not enough
GRANT USAGE ON SCHEMA public TO analyst;
仕組み
The table grant alone is not enough: without USAGE on the schema, every query fails with permission denied for schema public. ON ALL TABLES also covers views and materialized views, but not sequences; reading a serial column needs no sequence privilege, calling nextval() does. The grant applies only to tables that exist when it runs, so pair it with default privileges for future ones. Re-running it is harmless.
Variations
PostgreSQL: generated per-table script
PostgreSQLSELECT format('GRANT SELECT ON %I.%I TO analyst;', table_schema, table_name)
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE';
-- run the output; useful when only some tables should be granted
MySQL
MySQLGRANT SELECT ON mydb.* TO 'analyst'@'%';
-- database-wide, so it also covers tables created later;
-- per table: GRANT SELECT ON mydb.users TO 'analyst'@'%';
-- no FLUSH PRIVILEGES needed after GRANT
SQL Server
SQL ServerGRANT SELECT ON SCHEMA::dbo TO analyst;
-- covers every current and future table and view in dbo;
-- for a single table instead:
-- GRANT SELECT ON OBJECT::dbo.Users TO analyst;
Questions that come up
Why can my analyst see the tables but get errors on SELECT?
On PostgreSQL, 'permission denied for schema' means USAGE is missing, and 'permission denied for table' on a table created after the GRANT means it needs a fresh grant or default privileges. If queries succeed but return no rows, the table has row-level security enabled and no policy admits the analyst. Also check that the grant went to the schema the queries actually resolve to through search_path.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.