PostgreSQL: Restricting a User to a Single Database
This guide explains how to create a PostgreSQL user that can only connect to one specific database and has controlled permissions (read-only or read-write) within that database.
Key Concepts
Users and Roles are Global
In PostgreSQL, users (roles) are global, not per-database. You cannot create a user that exists only inside one database.
- Roles are stored in the global catalog (
pg_authid), shared by all databases in the cluster - Think of PostgreSQL as an apartment building: users are people with keycards, databases are apartments. You can't make a keycard that only exists in one apartment, but you can control which doors it opens.
Understanding Role Inheritance
PostgreSQL doesn't distinguish between "users" and "groups" - they're both roles:
| Type | Description |
|---|---|
| Login Role | A role with LOGIN attribute (can connect with password) |
| Group Role | A role without LOGIN (used to bundle privileges) |
The INHERIT attribute controls whether a role automatically gets privileges from roles it belongs to:
| Setting | Behavior |
|---|---|
INHERIT (default) | Role automatically uses parent role's privileges |
NOINHERIT | Role must explicitly SET ROLE to use parent privileges |
The "With Admin Option"
When granting membership with WITH ADMIN OPTION:
GRANT reporting_group TO alice WITH ADMIN OPTION;
This means:
- Alice inherits all privileges of
reporting_group - Alice can add/remove other users to/from
reporting_group - Alice does NOT become a superuser
Step-by-Step Guide (pgAdmin)
Restricting a user to one database requires two separate steps:
| Step | What it does | Where to run |
|---|---|---|
| Step 2 | Revoke CONNECT from other databases | Any database (cluster-level) |
| Step 3 | Grant read/write inside target database | Target database only |
Why two steps?
CONNECTpermission only allows login — it doesn't grant any data access. You must explicitly grant schema/table privileges for the user to see or modify data.
Step 1: Create the User
In pgAdmin's Browser panel:
- Expand your server > Right-click Login/Group Roles > Create > Login/Group Role
- Fill in:
- General tab: Name (e.g.,
myuser) - Definition tab: Password
- Privileges tab: Only check "Can login"
- General tab: Name (e.g.,
- Click Save
Step 2: Restrict Database Access (Revoke CONNECT from other databases)
What this does: Limits WHICH database the user can connect to.
Important: This step can be run from ANY database. It controls cluster-level connection permissions.
Open Query Tool in pgAdmin and run this script (replace the variables):
DO $$
DECLARE
target_role text := 'gongkar_testdb_user'; -- <-- change me
allowed_db text := 'gongkar-testdb'; -- <-- change me
db record;
BEGIN
RAISE NOTICE 'Databases (non-templates):';
FOR db IN
SELECT datname, datdba
FROM pg_database
WHERE datistemplate = false
ORDER BY datname
LOOP
RAISE NOTICE ' - %', db.datname;
END LOOP;
-- Always ensure the allowed DB is granted
EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I;', allowed_db, target_role);
-- Loop other DBs and try to revoke; skip special/system DBs
FOR db IN
SELECT datname, datdba
FROM pg_database
WHERE datistemplate = false
AND datname <> allowed_db
LOOP
-- Skip system / managed DBs you can't touch
IF db.datname IN ('template0','template1','postgres','rdsadmin') THEN
RAISE NOTICE 'Skipping system/managed DB: %', db.datname;
CONTINUE;
END IF;
BEGIN
EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM %I;', db.datname, target_role);
RAISE NOTICE 'Revoked CONNECT on % from %', db.datname, target_role;
-- Optional: also tighten PUBLIC so membership in PUBLIC can't bypass your revoke
EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM PUBLIC;', db.datname);
RAISE NOTICE 'Revoked CONNECT on % from PUBLIC', db.datname;
-- Keep DB owner able to connect (safety)
EXECUTE format('GRANT CONNECT ON DATABASE %I TO %s;', db.datname, (db.datdba::regrole)::text);
EXCEPTION
WHEN insufficient_privilege THEN
RAISE NOTICE 'Skipping % (insufficient privilege / not owner on RDS)', db.datname;
WHEN OTHERS THEN
RAISE NOTICE 'Skipping % due to: %', db.datname, SQLERRM;
END;
END LOOP;
RAISE NOTICE 'Done. % can only connect to % (subject to PUBLIC on untouchable DBs).',
target_role, allowed_db;
END
$$;
Note: The
\setcommand is a psql meta-command and does NOT work in pgAdmin's Query Tool. UseDOblocks withDECLAREinstead.
Step 3: Grant Read/Write Permissions Inside the Target Database
What this does: Controls WHAT the user can do inside the allowed database.
Important: You MUST connect to the target database first! In pgAdmin, right-click the target database > Query Tool, then run these commands.
After Step 2, the user can connect but has zero data access by default. Run one of these:
Read-only access:
GRANT USAGE ON SCHEMA public TO myuser;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO myuser;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO myuser;
-- Optional: for sequences
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO myuser;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON SEQUENCES TO myuser;
Read-write access:
GRANT USAGE ON SCHEMA public TO myuser;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO myuser;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO myuser;
Default Permissions Explained
When you create a new PostgreSQL user and only grant CONNECT:
| Privilege | Default | Effect |
|---|---|---|
| CONNECT on database | Must be granted | Log into the database |
| USAGE on schema | No | Access objects inside the schema |
| SELECT/INSERT/UPDATE/DELETE | No | Read/write data |
| CREATE on schema | No | Create new tables, views, etc. |
Important: If you only grant CONNECT, the user can log in but cannot see or modify any data.
Amazon RDS Considerations
On Amazon RDS for PostgreSQL:
- You cannot change privileges on
rdsadmindatabase (it's reserved) - You may not be owner of some databases
- The script above handles these cases with exception handling
Common error:
ERROR: permission denied for database rdsadmin
This is expected - the script skips system databases automatically.
Testing Your Configuration
- Create a new pgAdmin connection using the restricted user
- Try connecting to the allowed database - should work
- Try connecting to other databases - should fail
- Run
SELECT * FROM some_table;- should work (if read access granted) - Run
INSERT INTO some_table VALUES (...);- should fail for read-only users
Summary
| Action | SQL Command |
|---|---|
| Create user | CREATE USER username WITH PASSWORD 'password'; |
| Allow access to one DB | GRANT CONNECT ON DATABASE mydb TO username; |
| Revoke from others | REVOKE CONNECT ON DATABASE otherdb FROM username; |
| Schema access | GRANT USAGE ON SCHEMA public TO username; |
| Read-only access | GRANT SELECT ON ALL TABLES IN SCHEMA public TO username; |
| Read-write access | GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO username; |
Deep Dive: Roles, Group Roles, and Membership in PostgreSQL
The Unified Role System
The truth: PostgreSQL doesn't really separate "users" and "groups" — they're both just roles.
The only difference is a single attribute:
-
A "user" is simply a role that can log in:
CREATE ROLE alice LOGIN PASSWORD 'secret'; -- or equivalently: CREATE USER alice WITH PASSWORD 'secret'; -- CREATE USER is just an alias that adds LOGIN -
A "group" is simply a role without login privilege:
CREATE ROLE reporting_team NOLOGIN; -- or equivalently: CREATE ROLE reporting_team; -- NOLOGIN is the default
| Concept | PostgreSQL Term | SQL Attribute | Can Connect? |
|---|---|---|---|
| User | Login Role | LOGIN | Yes |
| Group | Group Role | NOLOGIN (default) | No |
Key insight:
CREATE USERis literally just an alias forCREATE ROLE ... LOGIN. There's no separate "user" object in PostgreSQL.
INHERIT vs NOINHERIT: Automatic vs Explicit Privilege Activation
The INHERIT attribute controls whether a role automatically gets privileges from its parent roles, or must explicitly activate them.
| Setting | Description | Effect |
|---|---|---|
INHERIT (default) | Role automatically uses parent role's privileges | User can immediately query tables without doing anything extra |
NOINHERIT | Role must explicitly SET ROLE to use parent privileges | User cannot access anything from parent role until they run SET ROLE |
Example of NOINHERIT in action:
-- Create a group with SELECT privileges
CREATE ROLE report_group;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO report_group;
-- Create a user with NOINHERIT
CREATE USER bob WITH PASSWORD 'secret' NOINHERIT;
GRANT report_group TO bob;
Now, if Bob logs in:
psql -U bob -d mydb
And tries:
SELECT * FROM sales;
He gets:
ERROR: permission denied for table sales
But if he runs:
SET ROLE report_group;
SELECT * FROM sales;
It works! That's what NOINHERIT does — it requires explicit activation of the parent role's privileges.
In pgAdmin: When you open the Privileges tab for a role, you'll see a checkbox "Inherit rights from parent roles":
- Checked →
INHERIT(default) — privileges are automatic - Unchecked →
NOINHERIT— must useSET ROLEto activate
When to use which:
| Use Case | Recommended | Why |
|---|---|---|
| Normal users (most cases) | INHERIT | Simpler: users automatically get privileges from group roles |
| Security-conscious / auditing | NOINHERIT | Forces explicit SET ROLE, making privilege use deliberate and traceable |
| Multi-role setups with least-privilege | NOINHERIT | Users log in with minimal access, elevate only when needed |
What is a "Parent Role"?
In PostgreSQL, there's no explicit "parent" property on a role. Instead, role membership defines the parent-child relationship.
GRANT parent_role TO child_role;
- The role you
GRANTis the parent (the one giving privileges) - The role you grant
TOis the child (the one receiving/inheriting privileges)
Example:
GRANT reporting_team TO alice;
-- ^^^^^^^^^^^^^^ ^^^^^
-- parent role child role
Here, reporting_team is the parent role, and alice is the child. Alice inherits privileges from reporting_team.
Note: A role can have multiple parents (belong to multiple groups), and a parent can have multiple children (multiple users in one group).
How Role Membership Works
Roles can be members of other roles, creating a hierarchy:
-- Create a group role (no login)
CREATE ROLE reporting_team;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting_team;
-- Create a user
CREATE USER alice WITH PASSWORD 'secret';
-- Make alice a member of reporting_team
GRANT reporting_team TO alice;
Now:
aliceinherits all privileges ofreporting_teamalicecan read all tables (becausereporting_teamhasSELECT)
The "With Admin Option" Explained
In pgAdmin's Membership tab, you'll see an "Admin?" column. This corresponds to the SQL clause WITH ADMIN OPTION.
GRANT reporting_team TO alice WITH ADMIN OPTION;
What this means:
| Capability | Without Admin | With Admin Option |
|---|---|---|
| Inherit group privileges | Yes | Yes |
| Add other users to the group | No | Yes |
| Remove users from the group | No | Yes |
| Become a superuser | No | No |
Example:
-- Alice has admin option on reporting_team
GRANT reporting_team TO alice WITH ADMIN OPTION;
-- Now Alice can do this:
GRANT reporting_team TO bob; -- Alice adds Bob to the group
-- But Alice CANNOT:
-- - Create new databases
-- - Drop tables she doesn't own
-- - Become superuser
Important:
WITH ADMIN OPTIONdoes NOT mean "database administrator." It only gives control over that specific role's membership, not global privileges.
Visualizing the Hierarchy
┌─────────────────┐
│ reporting_team │ (Group Role - NOLOGIN)
│ - SELECT on │
│ all tables │
└────────┬────────┘
│
┌──────────────┼──────────────┐
│ GRANT │ GRANT │ GRANT
│ (admin) │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ alice │ │ bob │ │ carol │
│ (LOGIN) │ │ (LOGIN) │ │ (LOGIN) │
└─────────┘ └─────────┘ └─────────┘
Can add Cannot add Cannot add
members members members
pgAdmin UI: Where to Find What
| What you want to do | Where in pgAdmin |
|---|---|
| See what groups a user belongs to | Edit Login Role > Membership tab |
| See what users belong to a group | Edit Group Role > Members tab |
| Grant admin option | Check the "Admin?" checkbox in Membership/Members tab |
| Create a new group role | Right-click Login/Group Roles > Create > uncheck "Can login" |
Practical Example: Read-Only vs Admin Users
-- Step 1: Create group roles for different access levels
CREATE ROLE readonly_users;
CREATE ROLE readwrite_users;
CREATE ROLE admin_users;
-- Step 2: Grant appropriate privileges to each group
GRANT USAGE ON SCHEMA public TO readonly_users;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_users;
GRANT USAGE ON SCHEMA public TO readwrite_users;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO readwrite_users;
GRANT ALL PRIVILEGES ON SCHEMA public TO admin_users;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO admin_users;
-- Step 3: Create users and assign to groups
CREATE USER analyst WITH PASSWORD 'pass1';
GRANT readonly_users TO analyst;
CREATE USER developer WITH PASSWORD 'pass2';
GRANT readwrite_users TO developer;
CREATE USER team_lead WITH PASSWORD 'pass3';
GRANT admin_users TO team_lead WITH ADMIN OPTION; -- can manage admin_users membership
Now:
analystcan only SELECTdevelopercan SELECT, INSERT, UPDATE, DELETEteam_leadhas all privileges AND can add/remove users fromadmin_users
FAQ
Q: Can't I just create the user on the specific database instead of public/global?
No, you can't. This is a common point of confusion.
In PostgreSQL, users (roles) are global, not per-database. You cannot create a user that exists only inside one database.
Why?
- PostgreSQL's role system works at the cluster level, not the database level
- When you run
CREATE USER, that role is created in the entire PostgreSQL cluster (all databases managed by that server instance) - Roles are stored in the global catalog (
pg_authid), which is shared by all databases
What you CAN do: Restrict what the user can access or do in each database by:
- Revoking
CONNECTon databases they shouldn't access - Only granting schema/table privileges on the specific database
Q: Why do Group Roles and User Roles have different UIs in pgAdmin?
Because pgAdmin's UI is designed to make it easier for humans to understand the distinction, even though PostgreSQL treats them almost the same under the hood.
| pgAdmin Object | PostgreSQL Equivalent | Notes |
|---|---|---|
| Login/Group Role | CREATE ROLE name WITH LOGIN | Can log in if LOGIN is set |
| Group Role | CREATE ROLE name NOLOGIN | Used to bundle privileges |
| Membership tab | GRANT group_role TO user_role; | User inherits group privileges |
The Definition tab for Login Roles shows "Password" and "Valid Until" fields (because users can log in), while Group Roles hide these since groups can't log in.
Q: What does "Inherit rights from parent roles" mean in pgAdmin?
This corresponds to the SQL clause [NO]INHERIT.
| Setting | Behavior |
|---|---|
| Checked (INHERIT - default) | The user automatically gets all privileges of any roles they're a member of |
| Unchecked (NOINHERIT) | They don't automatically inherit privileges; must run SET ROLE to use them |
Example with NOINHERIT:
CREATE USER bob WITH PASSWORD 'secret' NOINHERIT;
GRANT report_group TO bob;
If Bob logs in and tries SELECT * FROM sales; - he gets permission denied.
But if he runs:
SET ROLE report_group;
SELECT * FROM sales;
It works! NOINHERIT requires explicit activation of parent role's privileges.
When to use which:
- Normal users: Keep
INHERIT(simpler) - Security-conscious/auditing scenarios: Use
NOINHERIT(forces explicitSET ROLE, making privilege use deliberate and traceable)
Q: Where do I set the parent role in pgAdmin? I can't find it!
There's no explicit "parent" property. Role membership defines the relationship.
GRANT parent_role TO child_role;
In pgAdmin:
- Option 1: Edit a user (Login Role) > Membership tab > Check the boxes for group roles you want them to belong to
- Option 2: Edit a group role > Members tab > Add users there (inverse view)
Both do the same thing: GRANT group_role TO user;
Q: If I don't set permissions inside the database, will the user have read/write access?
No! By default, a new user with only CONNECT permission gets zero data access.
If you only run:
GRANT CONNECT ON DATABASE mydb TO myuser;
The user can log in, but if they try:
SELECT * FROM some_table;
They get:
ERROR: permission denied for table some_table
And if they try to create objects:
CREATE TABLE test (id int);
They get:
ERROR: permission denied for schema public
Bottom line: GRANT CONNECT only allows login. You must explicitly grant schema and table privileges for any data access.
Q: Why am I getting syntax error at or near "\" when running the script?
ERROR: syntax error at or near "\"
LINE 1: \set target_role 'gongkar_testdb_user'
The \set command is a psql meta-command, not standard SQL. It works in the psql command-line client but NOT in pgAdmin's Query Tool.
Solution: Use DO blocks with DECLARE instead:
DO $
DECLARE
target_role text := 'myuser';
allowed_db text := 'mydb';
BEGIN
-- your code here
END$;
Q: Why am I getting permission denied for database rdsadmin?
ERROR: permission denied for database rdsadmin
CONTEXT: SQL statement "REVOKE CONNECT ON DATABASE rdsadmin FROM myuser;"
You're on Amazon RDS for PostgreSQL. The rdsadmin database is reserved and managed by AWS - you cannot change its ACLs.
Solution: The pgAdmin-compatible script in this guide automatically skips system databases like rdsadmin, postgres, template0, and template1.
References
- PostgreSQL Documentation - CREATE ROLE. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/sql-createrole.html
- PostgreSQL Documentation - GRANT. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/sql-grant.html
- PostgreSQL Documentation - Role Membership. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/role-membership.html