GRANT assigns specific privileges on database objects to roles, controlling who can read, write, or administer them.
Use the GRANT statement to give users or roles precise privileges on databases, schemas, tables, sequences, functions, and more. It is the cornerstone of fine-grained access control.
GRANT lets you avoid one superuser for everything. You can hand out only the rights a developer, analyst, or app needs, keeping data safe and audits simple.
The format is GRANT privilege_list ON object_type object_name TO role_list [WITH GRANT OPTION]
. Replace each placeholder with your objects and roles.
Run GRANT SELECT ON public.sales TO analyst;
. The analyst
role can now query public.sales
but cannot modify it.
First make the schema owner execute GRANT CREATE ON SCHEMA reporting TO loader;
. Then log in as loader
and create tables freely inside reporting
.
Combine a direct GRANT with ALTER DEFAULT PRIVILEGES
:GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
Add WITH GRANT OPTION
. Example: GRANT SELECT ON customers TO team_lead WITH GRANT OPTION;
. The team_lead
may now pass SELECT to colleagues.
Create roles like reader
, writer
, admin
. Then GRANT reader TO alice;
. This keeps permissions tidy when staff changes.
Start with REVOKE ALL
if you inherit an environment with broad rights. Then grant back only what is necessary.
Run \dp tablename
in psql
. It shows who has which rights on the object.
Grant database-level CONNECT and TEMP rights to permit session creation and temp table usage. Everything else should be on schema or table level.
Yes. Use GRANT ALL PRIVILEGES ON table_name TO role;
. It maps to every valid object-level right.
No. GRANT adds privileges. Use REVOKE or ALTER DEFAULT PRIVILEGES to remove or change existing ones.
Run REVOKE privilege_list ON object FROM role;
. The change takes effect immediately for new queries.