// SQL snippet

Revoke all privileges

When someone leaves or a service is decommissioned, its access should go with it. Revoke table and sequence privileges in one pass rather than hunting them down object by object.

Main statement
PostgreSQL
Couvre également
SQL Server MySQL

The task

A contractor finished or a service was retired, and its role must lose every grant now rather than turning up in the next access audit.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM intern;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM intern;
-- and, for completeness, schema usage itself
REVOKE USAGE ON SCHEMA public FROM intern;

Fonctionnement

REVOKE ALL PRIVILEGES ON ALL TABLES removes every table-level privilege (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER and, on PostgreSQL 17+, MAINTAIN) from tables existing in the schema. It does not touch role membership, privileges granted to PUBLIC, or default privileges, so check pg_auth_members and pg_default_acl too. Each database in the cluster keeps its own grants, so repeat it per database.

Variations

MySQL

MySQL
-- ON mydb.* removes database-level grants only, and errors
-- (1141) if there are none. This form removes every global,
-- database, table, column and routine grant at once:
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'intern'@'%';
SHOW GRANTS FOR 'intern'@'%';  -- verify what remains

SQL Server

SQL Server
-- REVOKE ALL is deprecated and rejected for schemas (error
-- 4623); name the permissions
REVOKE SELECT, INSERT, UPDATE, DELETE, EXECUTE
    ON SCHEMA::dbo FROM intern;
-- DENY beats grants from role membership too, db_owner
-- included (not sysadmin or the dbo user itself);
-- ALTER ROLE ... DROP MEMBER removes the memberships
DENY SELECT ON SCHEMA::dbo TO intern;

Questions that come up

Can I revoke if the role owns objects?

You can, but it changes little: an owner's rights come from ownership, not from grants, and PostgreSQL refuses DROP ROLE while the role owns objects or holds privileges. In each database run REASSIGN OWNED BY intern TO app_owner, then DROP OWNED BY intern, which also revokes every privilege granted to intern there. After that DROP ROLE intern succeeds.

Keep reading

// snippets are better with a schema brain

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.