This cheatsheet provides essential PostgreSQL commands for managing databases, users, and data. It covers installation, setup, user roles, database creation, table operations, and backup/restore procedures.
- Getting Started with PostgreSQL on Mac OS X
- PostgreSQL Schema Tutorial
- PostgreSQL Roles and Permissions Management
- PostgreSQL Cheat Sheet
- PostgreSQL SERIAL Data Type
- Create Users, Databases, and Grant Access in PostgreSQL
Follow these steps to install and start PostgreSQL on your system.
brew install postgresql
brew services start postgresql
psql postgres
A collection of frequently used PostgreSQL commands for database and user management.
Create a new database:
CREATE DATABASE foo;
List all databases:
\l
Switch to a different database:
\c dbname
Create a new role with login and password:
CREATE ROLE user1 WITH LOGIN PASSWORD 'secret';
List all roles:
\du
Allow a role to create databases:
ALTER ROLE user1 CREATEDB;
Exit the current psql session and log in as a specific user:
psql postgres -U user1
Create a new user with an encrypted password:
CREATE USER testuser with encrypted password 'sekretpw';
Grant all privileges on a database to a role:
GRANT ALL PRIVILEGES ON DATABASE "foo" to user1;
Grant all privileges on a database to a user:
GRANT ALL PRIVILEGES ON database foo TO testuser;
Create a table with an auto-incremental primary key:
CREATE TABLE fruits(id SERIAL PRIMARY KEY, name VARCHAR NOT NULL);
INSERT INTO fruits(id,name) VALUES(DEFAULT,'Apple');
List tables in the current database:
\dt
\dt+
Backup a database:
pg_dump -h 127.0.0.1 -U postgres -p 5432 dbname > dbname.bak
Restore a database:
psql -h dbname.x.eu-west-1.rds.amazonaws.com -U postgres dbname < dbname.bak