Cheatsheet - PostgreSQL
For psql, check out Cheatsheet - psql
Connecting & psql Meta-Commands
Once you're in the psql interactive terminal, you can use these helpful "meta-commands," which are preceded by a backslash.
- Connect to a database:
\c <database_name> - List all databases:
\lor\list - List all tables in the current database:
\dt - Describe a table (columns, types, etc.):
\d <table_name> - List all users and their roles:
\du - Get help on a specific SQL command:
\h <SQL_COMMAND>(e.g.,\h CREATE TABLE) - Quit psql:
\q - Toggle expanded display for wide results:
\x
Data Definition Language (DDL)
These commands are used to define and manage the structure of your database.
-
Create a Database:
CREATE DATABASE <database_name>; -
Drop a Database:
DROP DATABASE <database_name>; -
Create a Table:
CREATE TABLE <table_name> (
column1_name data_type constraints,
column2_name data_type,
...
);
- Create a Table with a Primary Key:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
- Drop a Table:
DROP TABLE <table_name>; - Alter a Table:
- Add a column:
ALTER TABLE <table_name> ADD COLUMN <new_column_name> data_type; - Drop a column:
ALTER TABLE <table_name> DROP COLUMN <column_name>; - Rename a column:
ALTER TABLE <table_name> RENAME COLUMN <old_name> TO <new_name>; - Change a column's data type:
ALTER TABLE <table_name> ALTER COLUMN <column_name> TYPE new_data_type;
Data Manipulation Language (DML)
Use these commands to interact with the data within your tables.
- Insert a Single Row:
INSERT INTO <table_name> (column1, column2) VALUES (value1, value2);
- Insert Multiple Rows:
INSERT INTO <table_name> (column1, column2) VALUES
(value1, value2),
(value3, value4),
(value5, value6);
- Update Records:
UPDATE <table_name> SET column1 = new_value WHERE condition;
- Delete Records:
DELETE FROM <table_name> WHERE condition;
Data Query Language (DQL)
These commands are used to retrieve data from your database.
- Select All Columns:
SELECT * FROM <table_name>; - Select Specific Columns:
SELECT column1, column2 FROM <table_name>; - Filtering with WHERE:
SELECT * FROM <table_name> WHERE condition; - Sorting with ORDER BY:
SELECT * FROM <table_name> ORDER BY column_name ASC|DESC; - Limiting Results:
SELECT * FROM <table_name> LIMIT 10; - Unique Values:
SELECT DISTINCT column_name FROM <table_name>; - Aggregate Functions:
AVG(),COUNT(),MAX(),MIN(),SUM() - Grouping Data:
SELECT column1, COUNT(*) FROM <table_name> GROUP BY column1; - Filtering Groups:
SELECT column1, COUNT(*) FROM <table_name> GROUP BY column1 HAVING COUNT(*) > 5;
Joins
Combine rows from two or more tables based on a related column.
- Inner Join:
SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.table1_id; - Left Join:
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id; - Right Join:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.id = table2.table1_id; - Full Outer Join:
SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.id = table2.table1_id;
Common Data Types
PostgreSQL supports a wide range of data types.
- Numeric:
INTEGER,BIGINT,NUMERIC(precision, scale),REAL,DOUBLE PRECISION,SERIAL - Character:
VARCHAR(n),CHAR(n),TEXT - Date/Time:
DATE,TIME,TIMESTAMP,INTERVAL - Boolean:
BOOLEAN - JSON:
JSON,JSONB - UUID:
UUID
User and Permission Management
These commands are used to manage users and their access to database objects.
- Create a User:
CREATE USER <username> WITH PASSWORD '<password>'; - Drop a User:
DROP USER <username>; - Grant Privileges:
GRANT ALL PRIVILEGES ON DATABASE <database_name> TO <username>; - Grant specific permissions on a table:
GRANT SELECT, INSERT, UPDATE, DELETE ON <table_name> TO <username>; - Grant all permissions on all tables in a schema:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema_name> TO <username>; - Revoke Privileges:
REVOKE ALL PRIVILEGES ON DATABASE <database_name> FROM <username>;
Backup and Restore
Use these command-line utilities to back up and restore your databases.
Backup a Database:
pg_dump -U <username> -W -F c -f <backup_file.dump> <database_name>
-U: Specifies the user to connect as.-W: Forces a password prompt.-F c: Specifies the output format as custom (compressed).-f: Specifies the output file.
Restore a Database:
pg_restore -U <username> -W -d <database_name> <backup_file.dump>
-d: Specifies the database to restore to.
Start server
$ postgres -D /path/to/data
# start in the background
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
Check pg_hba.conf
pg_hba.conf controls client authentication (HBA stands for host-based authentication.)
$ find / -name "pg_hba.conf"
pg_hba.conf file format: a set of records, one per line.
Check readiness
Use pg_isready