Comprehensive PostgreSQL Commands Cheat Sheet

This cheat sheet includes a wide range of PostgreSQL commands useful for database administration and interaction:

Command Description
psql -U [username] -d [database] Connect to a PostgreSQL database under a specific user.
\q Quit psql session.
CREATE DATABASE [database]; Create a new database.
DROP DATABASE [database]; Delete a database.
\l or \list List all databases in PostgreSQL.
CREATE USER [username] WITH PASSWORD '[password]'; Create a new user with a password.
DROP USER [username]; Remove a user from PostgreSQL.
\du List all users and their roles.
CREATE TABLE [table] (...); Create a new table.
ALTER TABLE [table] ...; Change a table’s structure.
DROP TABLE [table]; Delete a table.
\dt List all tables in the current database.
\d [table] Show table definition including columns, column types, constraints, etc.
SELECT * FROM [table]; Select all data from a table.
INSERT INTO [table] VALUES (...); Insert data into a table.
UPDATE [table] SET [column] = [value] WHERE [condition]; Update data in a table.
DELETE FROM [table] WHERE [condition]; Delete data from a table.
BEGIN; ... COMMIT; Begin a transaction, and commit the transaction.
BEGIN; ... ROLLBACK; Begin a transaction, and roll it back if needed.
pg_dump [database] > [file] Backup a database to a file.
pg_restore -d [database] [file] Restore a database from a file.
\i [filename] Execute SQL commands from a file.
EXPLAIN [query]; Show the execution plan of a SQL statement.
\h Get help on SQL commands.
\set Show or set psql variables.