Managing Users and Privileges
Commands for creating a new application account, or for checking "why can't this account read this table" and "who holds DBA privileges". In all three databases, the recommended approach is to collect privileges in a role and grant the role to users rather than granting privileges directly to users. Passwords can remain in command history and logs, so the examples below use placeholders; supply the real values from an interactive tool or a secrets store.
Oracle
Required privileges: SELECT_CATALOG_ROLE for queries; CREATE USER/ALTER USER to create or modify users; ADMIN OPTION on the privilege or GRANT ANY PRIVILEGE to grant privileges. In a multitenant database, you create local users in the PDB you are connected to (common users in the root have names starting with C##).
Creating users and roles
CREATE USER app IDENTIFIED BY "<password>"
DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp
QUOTA 10G ON users
PROFILE app_profile;
GRANT CREATE SESSION TO app;
CREATE ROLE sales_read;
GRANT SELECT ON sales.orders TO sales_read;
GRANT SELECT ON sales.customers TO sales_read;
GRANT sales_read TO app;
- 19c has no privilege that grants on a whole schema at once, so
GRANTobject by object (in 23ai+:GRANT SELECT ANY TABLE ON SCHEMA sales TO ...). - Privileges received through a role do not apply to PL/SQL definer's-rights procedures or to view creation. In those cases,
GRANTdirectly.
User status
SELECT username, account_status, lock_date, expiry_date, profile,
default_tablespace, created, last_login -- last_login: 12c+
FROM dba_users
WHERE oracle_maintained = 'N' -- 12c+, excludes system accounts
ORDER BY username;
account_statusappears as combinations such asOPEN,LOCKED(locked by an administrator),LOCKED(TIMED)(locked by failed logins),EXPIRED, andEXPIRED(GRACE)(grace period).
Who has what
-- system privileges
SELECT grantee, privilege, admin_option FROM dba_sys_privs WHERE grantee = 'APP';
-- object privileges
SELECT grantee, owner, table_name, privilege, grantable
FROM dba_tab_privs WHERE grantee IN ('APP', 'SALES_READ');
-- roles (follows roles nested inside roles)
SELECT LPAD(' ', 2 * (LEVEL - 1)) || granted_role AS role_tree, admin_option, default_role
FROM dba_role_privs
START WITH grantee = 'APP'
CONNECT BY PRIOR granted_role = grantee;
-- accounts with the DBA role or ANY privileges
SELECT grantee FROM dba_role_privs WHERE granted_role = 'DBA'
UNION
SELECT grantee FROM dba_sys_privs WHERE privilege LIKE '%ANY%';
dba_tab_privsshows only privileges granted directly. For those received through a role, follow the role tree and look at that role's privileges.
Unlocking and resetting passwords
ALTER USER app ACCOUNT UNLOCK;
ALTER USER app IDENTIFIED BY "<password>" ACCOUNT UNLOCK;
ALTER USER app PASSWORD EXPIRE; -- force a change at next login
ALTER USER app ACCOUNT LOCK; -- departed staff, deactivated accounts
WARNING After a password change, connection pools and batch jobs that use the account fail from their next connection. Check whether you can change the application configuration first. Do not use
PASSWORD EXPIREon application accounts whose application has no password change screen.
Profiles: login failure lockout and password expiry
SELECT profile, resource_name, limit
FROM dba_profiles
WHERE resource_type = 'PASSWORD'
ORDER BY profile, resource_name;
ALTER PROFILE app_profile LIMIT
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_LOCK_TIME 1/24 -- in days: 1 hour
PASSWORD_LIFE_TIME UNLIMITED;
- The
DEFAULTprofile hasPASSWORD_LIFE_TIME 180(days) andFAILED_LOGIN_ATTEMPTS 10. This is a common reason an application account suddenly fails one day withORA-28001(expired).
WARNING Changing a profile applies immediately to every user of that profile. The
DEFAULTprofile is used by all accounts with no profile specified.
PostgreSQL
Required privileges: creating roles requires superuser or CREATEROLE (in 16+, CREATEROLE can administer only roles it created); granting object privileges requires being the object owner.
In PostgreSQL, both users and groups are roles. CREATE USER is the same as CREATE ROLE ... LOGIN.
Creating roles and granting privileges
CREATE ROLE sales_read NOLOGIN;
GRANT CONNECT ON DATABASE sales TO sales_read;
GRANT USAGE ON SCHEMA sales TO sales_read;
GRANT SELECT ON ALL TABLES IN SCHEMA sales TO sales_read; -- only tables that exist now
CREATE ROLE app LOGIN PASSWORD '<password>' CONNECTION LIMIT 50;
GRANT sales_read TO app;
- To read a table, all of database
CONNECT, schemaUSAGE, and tableSELECTare required. If any one is missing, you getpermission denied. - In psql, changing the password with
\password appkeeps it from appearing in plain text in the server log or history. - 14+ has built-in roles
pg_read_all_dataandpg_write_all_datathat read or write all tables. - In 15+, the
CREATEprivilege on thepublicschema is no longer granted toPUBLICby default.
Granting privileges on tables created in the future
ALTER DEFAULT PRIVILEGES FOR ROLE sales_owner IN SCHEMA sales
GRANT SELECT ON TABLES TO sales_read;
SELECT pg_get_userbyid(defaclrole) AS owner, defaclnamespace::regnamespace AS schema,
defaclobjtype, defaclacl
FROM pg_default_acl;
- Default privileges apply only to objects created by the role named in
FOR ROLE. The most common mistake is that they do not apply when a table is created by a different account.
Listing roles and memberships
\du is psql-only, so in other tools, query the catalog directly.
SELECT rolname, rolsuper, rolcanlogin, rolcreaterole, rolcreatedb,
rolreplication, rolbypassrls, rolconnlimit, rolvaliduntil
FROM pg_roles
WHERE rolname NOT LIKE 'pg\_%'
ORDER BY rolname;
SELECT m.rolname AS member, r.rolname AS granted_role, am.admin_option
FROM pg_auth_members am
JOIN pg_roles r ON r.oid = am.roleid
JOIN pg_roles m ON m.oid = am.member
ORDER BY member;
- In 16+,
pg_auth_membershasinherit_optionandset_option, so a role can be granted without automatically inheriting its privileges.
Looking up table privileges
SELECT grantee, table_schema, table_name, privilege_type, is_grantable
FROM information_schema.role_table_grants
WHERE table_schema = 'sales'
ORDER BY grantee, table_name;
-- check directly whether it is actually allowed (including role inheritance)
SELECT has_table_privilege('app', 'sales.orders', 'SELECT');
SELECT has_schema_privilege('app', 'sales', 'USAGE');
information_schema.role_table_grantsshows only privileges granted by or to roles the querying user belongs to. To see everything, expandpg_class.relaclwithaclexplode().
Blocking and expiring accounts
ALTER ROLE app NOLOGIN; -- forbid login (privileges and objects are kept)
ALTER ROLE app VALID UNTIL '2026-12-31'; -- password expiry time
ALTER ROLE app PASSWORD '<password>';
- PostgreSQL has no built-in feature to lock an account after a number of failed logins. Use the
auth_delayextension (contrib) to add a delay after a failure, or the lockout policy of external authentication (LDAP, etc.).
Connection rules: pg_hba.conf
SELECT line_number, type, database, user_name, address, netmask, auth_method, error
FROM pg_hba_file_rules -- 10+, by default only superusers can query it
ORDER BY line_number;
SELECT pg_reload_conf(); -- apply after editing the file
- The first matching line from the top applies. If a broad rule is above, the narrower rules below it are never used.
- A line with a value in the
errorcolumn has a syntax error and is ignored on reload. Check before applying. - For password methods, use
scram-sha-256(the defaultpassword_encryptionin 14+).trustlets anyone connect without a password.
Dropping a role
-- run in each database where the role owns objects or has been granted privileges
REASSIGN OWNED BY app TO sales_owner;
DROP OWNED BY app;
-- after cleaning up in every database
DROP ROLE app;
WARNING
DROP OWNEDdrops the objects owned by that role (including tables). Always hand over ownership first withREASSIGN OWNED. Both commands apply only to the database where they are run, so repeat them in each database.
SQL Server
Required privileges: ALTER ANY LOGIN to manage logins; ALTER ANY USER to manage database users; ALTER ANY ROLE or ownership of the role to manage role members.
SQL Server has two levels. A LOGIN is an account that enters the instance (master, sys.server_principals), and a USER is an account inside a database (sys.database_principals). The two are linked by SID.
Creating logins and users
USE master;
CREATE LOGIN app WITH PASSWORD = N'<password>',
DEFAULT_DATABASE = sales, CHECK_POLICY = ON, CHECK_EXPIRATION = OFF;
-- Windows account: CREATE LOGIN [CORP\app_svc] FROM WINDOWS;
USE sales;
CREATE USER app FOR LOGIN app WITH DEFAULT_SCHEMA = dbo;
CREATE ROLE sales_read;
GRANT SELECT ON SCHEMA::sales TO sales_read; -- all current and future objects in the schema
ALTER ROLE sales_read ADD MEMBER app;
- With
CHECK_POLICY = ON, the Windows password policy (complexity, failure lockout) applies.CHECK_EXPIRATIONalso enforces expiry. - The built-in roles
db_datareaderanddb_datawriterapply to every table in the database, so their scope is broad.
Login list and status
SELECT sp.name, sp.type_desc, sp.is_disabled, sp.default_database_name, sp.create_date,
sl.is_policy_checked, sl.is_expiration_checked,
LOGINPROPERTY(sp.name, 'IsLocked') AS is_locked,
LOGINPROPERTY(sp.name, 'IsExpired') AS is_expired,
LOGINPROPERTY(sp.name, 'BadPasswordCount') AS bad_pw_count,
LOGINPROPERTY(sp.name, 'PasswordLastSetTime') AS pw_last_set
FROM sys.server_principals sp
LEFT JOIN sys.sql_logins sl ON sl.principal_id = sp.principal_id
WHERE sp.type IN ('S', 'U', 'G') AND sp.name NOT LIKE '##%'
ORDER BY sp.name;
-- members of server roles such as sysadmin
SELECT r.name AS server_role, m.name AS member
FROM sys.server_role_members rm
JOIN sys.server_principals r ON r.principal_id = rm.role_principal_id
JOIN sys.server_principals m ON m.principal_id = rm.member_principal_id
ORDER BY r.name, m.name;
type:SSQL login,UWindows user,GWindows group.
Looking up database permissions
-- role members
SELECT r.name AS db_role, m.name AS member
FROM sys.database_role_members rm
JOIN sys.database_principals r ON r.principal_id = rm.role_principal_id
JOIN sys.database_principals m ON m.principal_id = rm.member_principal_id
ORDER BY r.name, m.name;
-- directly granted permissions
SELECT pr.name AS principal, pr.type_desc, pe.state_desc, pe.permission_name, pe.class_desc,
CASE pe.class
WHEN 0 THEN DB_NAME()
WHEN 1 THEN OBJECT_SCHEMA_NAME(pe.major_id) + '.' + OBJECT_NAME(pe.major_id)
WHEN 3 THEN SCHEMA_NAME(pe.major_id)
END AS securable
FROM sys.database_permissions pe
JOIN sys.database_principals pr ON pr.principal_id = pe.grantee_principal_id
WHERE pr.name NOT IN ('public', 'guest')
ORDER BY pr.name, securable;
-- permissions actually held (including roles)
EXECUTE AS USER = 'app';
SELECT * FROM fn_my_permissions('sales.orders', 'OBJECT');
REVERT;
- A permission with
state_descofDENYtakes precedence over aGRANTreceived through a role.
Unlocking and disabling
ALTER LOGIN app WITH PASSWORD = N'<password>' UNLOCK;
ALTER LOGIN app DISABLE; -- forbid login (users and permissions are kept)
ALTER LOGIN app ENABLE;
WARNING After a password change, every application that uses the login fails from its next connection.
DISABLEdoes not disconnect sessions that are already connected, so disconnect them too if needed (see 01-sessions).
Orphaned users: logins and broken users after a restore
If you restore a database on a different server, there is no login matching the database user's SID, so the user cannot connect.
USE sales;
SELECT dp.name, dp.sid, dp.type_desc
FROM sys.database_principals dp
LEFT JOIN sys.server_principals sp ON sp.sid = dp.sid
WHERE dp.type = 'S'
AND dp.authentication_type_desc = 'INSTANCE'
AND dp.principal_id > 4
AND sp.sid IS NULL;
-- relink to the login with the same name (instead of sp_change_users_login)
ALTER USER app WITH LOGIN = app;
- To prevent this from the start, create the login with the original server's SID:
CREATE LOGIN app WITH PASSWORD = N'<password>', SID = 0x...;(get the SID fromsys.server_principalson the original server). - In an availability group, create the login with the same SID on the secondary replicas too, so users can connect immediately after a failover.