Managing PostgreSQL databases and users from the command line
PostgreSQL includes powerful command‑line tools that allow administrators to create, modify, and delete databases and users. On ruachost.com, you can manage PostgreSQL directly from the terminal for advanced control and automation.
Why Use the Command Line?
Section titled “Why Use the Command Line?”- Faster than using a web interface.
- Enables scripting and automation.
- Provides full access to PostgreSQL features.
- Essential for developers and system administrators.
Creating PostgreSQL Users
Section titled “Creating PostgreSQL Users”-
Log in to your server via SSH.
-
Switch to the PostgreSQL superuser:
Terminal window su - postgres -
Create a new user interactively:
Terminal window createuser --interactive --pwprompt- Enter the username.
- Enter and confirm the password.
- Choose whether the user is a superuser.
- Choose whether the user can create databases.
- Choose whether the user can create other roles.
Creating PostgreSQL Databases
Section titled “Creating PostgreSQL Databases”-
Log in as the PostgreSQL superuser:
Terminal window su - postgres -
Create a database owned by a specific user:
Terminal window createdb -O username dbname- Replace
usernamewith the database owner. - Replace
dbnamewith the database name.
- Replace
???? Tip: Users with permission to create databases can run:
createdb dbnameGranting User Privileges
Section titled “Granting User Privileges”-
Connect to PostgreSQL:
Terminal window psql -U postgres -
Grant privileges:
GRANT ALL PRIVILEGES ON DATABASE dbname TO username;- Replace
dbnamewith the database name. - Replace
usernamewith the user.
- Replace
Deleting PostgreSQL Databases
Section titled “Deleting PostgreSQL Databases”-
Log in as the PostgreSQL superuser.
-
Run:
Terminal window dropdb dbname⚠️ Warning: This deletes the database and all its data immediately without confirmation.
Deleting PostgreSQL Users
Section titled “Deleting PostgreSQL Users”-
Log in as the PostgreSQL superuser.
-
Run:
Terminal window dropuser username⚠️ Important: You cannot drop a user if they own any databases or objects.
- First, reassign ownership or drop the database.