PostgreSQL - How to Create a User with Access to Only One Database

December 17, 2025

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:

TypeDescription
Login RoleA role with LOGIN attribute (can connect with password)
Group RoleA role without LOGIN (used to bundle privileges)

The INHERIT attribute controls whether a role automatically gets privileges from roles it belongs to:

SettingBehavior
INHERIT (default)Role automatically uses parent role's privileges
NOINHERITRole 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:

StepWhat it doesWhere to run
Step 2Revoke CONNECT from other databasesAny database (cluster-level)
Step 3Grant read/write inside target databaseTarget database only

Why two steps? CONNECT permission 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:

  1. Expand your server > Right-click Login/Group Roles > Create > Login/Group Role
  2. Fill in:
    • General tab: Name (e.g., myuser)
    • Definition tab: Password
    • Privileges tab: Only check "Can login"
  3. 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 \set command is a psql meta-command and does NOT work in pgAdmin's Query Tool. Use DO blocks with DECLARE instead.

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:

PrivilegeDefaultEffect
CONNECT on databaseMust be grantedLog into the database
USAGE on schemaNoAccess objects inside the schema
SELECT/INSERT/UPDATE/DELETENoRead/write data
CREATE on schemaNoCreate 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 rdsadmin database (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

  1. Create a new pgAdmin connection using the restricted user
  2. Try connecting to the allowed database - should work
  3. Try connecting to other databases - should fail
  4. Run SELECT * FROM some_table; - should work (if read access granted)
  5. Run INSERT INTO some_table VALUES (...); - should fail for read-only users

Summary

ActionSQL Command
Create userCREATE USER username WITH PASSWORD 'password';
Allow access to one DBGRANT CONNECT ON DATABASE mydb TO username;
Revoke from othersREVOKE CONNECT ON DATABASE otherdb FROM username;
Schema accessGRANT USAGE ON SCHEMA public TO username;
Read-only accessGRANT SELECT ON ALL TABLES IN SCHEMA public TO username;
Read-write accessGRANT 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
ConceptPostgreSQL TermSQL AttributeCan Connect?
UserLogin RoleLOGINYes
GroupGroup RoleNOLOGIN (default)No

Key insight: CREATE USER is literally just an alias for CREATE 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.

SettingDescriptionEffect
INHERIT (default)Role automatically uses parent role's privilegesUser can immediately query tables without doing anything extra
NOINHERITRole must explicitly SET ROLE to use parent privilegesUser 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 use SET ROLE to activate

When to use which:

Use CaseRecommendedWhy
Normal users (most cases)INHERITSimpler: users automatically get privileges from group roles
Security-conscious / auditingNOINHERITForces explicit SET ROLE, making privilege use deliberate and traceable
Multi-role setups with least-privilegeNOINHERITUsers 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 GRANT is the parent (the one giving privileges)
  • The role you grant TO is 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:

  • alice inherits all privileges of reporting_team
  • alice can read all tables (because reporting_team has SELECT)

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:

CapabilityWithout AdminWith Admin Option
Inherit group privilegesYesYes
Add other users to the groupNoYes
Remove users from the groupNoYes
Become a superuserNoNo

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 OPTION does 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 doWhere in pgAdmin
See what groups a user belongs toEdit Login Role > Membership tab
See what users belong to a groupEdit Group Role > Members tab
Grant admin optionCheck the "Admin?" checkbox in Membership/Members tab
Create a new group roleRight-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:

  • analyst can only SELECT
  • developer can SELECT, INSERT, UPDATE, DELETE
  • team_lead has all privileges AND can add/remove users from admin_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:

  1. Revoking CONNECT on databases they shouldn't access
  2. 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 ObjectPostgreSQL EquivalentNotes
Login/Group RoleCREATE ROLE name WITH LOGINCan log in if LOGIN is set
Group RoleCREATE ROLE name NOLOGINUsed to bundle privileges
Membership tabGRANT 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.

SettingBehavior
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 explicit SET 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

  1. PostgreSQL Documentation - CREATE ROLE. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/sql-createrole.html
  2. PostgreSQL Documentation - GRANT. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/sql-grant.html
  3. PostgreSQL Documentation - Role Membership. (n.d.). Retrieved December 17, 2025, from https://www.postgresql.org/docs/current/role-membership.html

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-17). PostgreSQL - How to Create a User with Access to Only One Database. https://caiborui.com/blog/2025-12-17-en-postgresql-user-permissions-restrict-to-single-database

@misc{borui2025-6fec6a3b,
  author = {borui},
  title = {{PostgreSQL - How to Create a User with Access to Only One Database}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-17-en-postgresql-user-permissions-restrict-to-single-database}
}