// SQL snippet

List a user's privileges

Access reviews and 'why can't this user read X' questions both start the same way: list what the role can actually do. Each engine has its own view of that.

Main statement
PostgreSQL
Deckt außerdem ab
SQL Server MySQL SQLite

The task

Permission denied on a table that should be reachable, or a security questionnaire asking what a service account may do, both need the actual grant list before anything else.

The snippet

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

PostgreSQL
SELECT table_schema, table_name, privilege_type, is_grantable
FROM information_schema.table_privileges
WHERE grantee = 'analyst'
ORDER BY table_schema, table_name, privilege_type;

So funktioniert es

information_schema.table_privileges lists grants made directly to the role, and on PostgreSQL only rows the current user is allowed to see. Rights inherited through role membership or PUBLIC do not appear; has_table_privilege('analyst', 'public.orders', 'SELECT') answers the effective question for one table. is_grantable shows whether the role can pass the privilege on. Column-level grants are in information_schema.column_privileges.

Variations

MySQL

MySQL
SHOW GRANTS FOR 'analyst'@'%';
-- also show what the session user has:
SHOW GRANTS FOR CURRENT_USER();

SQL Server

SQL Server
SELECT dp.class_desc, dp.state_desc, dp.permission_name,
       CASE dp.class
         WHEN 0 THEN DB_NAME()
         WHEN 1 THEN OBJECT_SCHEMA_NAME(dp.major_id) + '.'
                     + OBJECT_NAME(dp.major_id)
         WHEN 3 THEN SCHEMA_NAME(dp.major_id)
       END AS securable
FROM sys.database_permissions dp
WHERE dp.grantee_principal_id = DATABASE_PRINCIPAL_ID('analyst')
ORDER BY dp.class, securable;

SQLite

SQLite
-- SQLite has no users or GRANT; whoever can open the file
-- can read it, so access is controlled by file permissions

Questions that come up

The user can read a table but no grant shows up. Why?

The access is inherited. On PostgreSQL the role may be a member of another role that holds the grant, or the grant went to PUBLIC; on SQL Server it may come through a database role, a Windows or Entra group, or the dbo user. Check pg_auth_members or sys.database_role_members, and on SQL Server run SELECT * FROM fn_my_permissions('dbo.Orders', 'OBJECT') while impersonating the user with EXECUTE AS USER.

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.