How do you grant a read-only user access to all current and future tables?

IntermediateConceptPostgreSQL
Answer

Short answer

Grant CONNECT on the database, USAGE on the schema, SELECT on all existing tables, and set ALTER DEFAULT PRIVILEGES so tables created later are readable too. (Postgres 14+ also has the built-in pg_read_all_data role.)

Steps

CREATE ROLE reporting WITH LOGIN PASSWORD 'R3ad-Only!';
GRANT CONNECT ON DATABASE shop TO reporting;
\c shop
GRANT USAGE ON SCHEMA public TO reporting;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO reporting;

-- future tables created BY shop_migrator in public
ALTER DEFAULT PRIVILEGES FOR ROLE shop_migrator IN SCHEMA public
  GRANT SELECT ON TABLES TO reporting;

The common trap

GRANT SELECT ON ALL TABLES only covers tables that exist now. Next week a migration creates a table and reporting gets permission denied. Default privileges fix that — but they apply to objects created by the role named in FOR ROLE.

Shortcut (PG 14+)

GRANT pg_read_all_data TO reporting;      -- read everything in every database

What to say in the interview

"CONNECT on the database, USAGE on the schema, SELECT on all tables and sequences, plus ALTER DEFAULT PRIVILEGES for the role that creates tables so future tables are covered. On 14+ pg_read_all_data is a quick option if cluster-wide read is acceptable."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL