Skip to main content
Reference Guide to PostgreSQL Commands and Syntax:

PostgreSQL cheat sheet

Summary

This PostgreSQL cheat sheet covers everything from basic connections and SQL queries to advanced features like window functions and transactions. It includes commands for database management, DDL/DML operations, joins, constraints, user permissions, data types, and psql meta-commands.

Introduction #

This cheat sheet provides you with a structured overview of the most important PostgreSQL (Postgres) commands. PostgreSQL is an open-source relational database management system (RDBMS) that uses the Structured Query Language (SQL) for interacting with databases.

Use this as a reference for basic queries, Data Definition Language (DDL), Data Manipulation Language (DML), connection options, user roles, and administrative tasks.

Connecting to PostgreSQL #

This section covers how to establish a connection to a PostgreSQL database using the psql command-line interface.

OptionExampleDescription
psql -U username -d dbnamepsql -U john -d inventoryConnect to the inventory database as user john.
psql -h host -p portpsql -h localhost -p 5432Specify host and port when connecting.
psql -Wpsql -W -U johnPrompt for password before connecting.
\c dbname\c salesConnect to the sales database within psql.
\conninfo\conninfoDisplay information about the current database connection.
\l\lList all databases in psql.
\q\qQuit the psql session.

Basic SQL commands #

These are the fundamental SQL statements used to query and retrieve data from tables.

OptionExampleDescription
SELECTSELECT * FROM employees;Retrieve all rows from the employees table.
WHERESELECT * FROM employees WHERE department = 'HR';Filter rows based on a condition.
BETWEENSELECT * FROM products WHERE price BETWEEN 10 AND 20;Filter rows within a specified range (inclusive).
LIKE/ILIKESELECT * FROM users WHERE name LIKE 'A%';Filter using pattern matching (ILIKE is case-insensitive).
ORDER BYSELECT name FROM employees ORDER BY name;Sort result by one or more columns.
LIMITSELECT * FROM employees LIMIT 5;Limit result to a specific number of rows.
DISTINCTSELECT DISTINCT department FROM employees;Return unique values only.

Data Definition Language (DDL) #

DDL statements are used to define, modify, and delete database structures like databases, tables, and indexes.

Databases #

These commands manage the creation and deletion of entire databases.

OptionExampleDescription
CREATE DATABASECREATE DATABASE company;Create a new database.
DROP DATABASEDROP DATABASE company;Delete a database permanently.

Tables #

Table commands define the structure of your data, allowing you to create, alter, and drop tables.

OptionExampleDescription
CREATE TABLECREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);Create a new table with specified columns.
DROP TABLEDROP TABLE users;Delete an existing table.
ALTER TABLEALTER TABLE users ADD COLUMN email TEXT;Modify the structure of an existing table.
RENAME TABLEALTER TABLE employees RENAME TO staff;Rename an existing table.
TRUNCATE TABLETRUNCATE TABLE employees;Remove all rows from a table without deleting it.

Indexes #

Indexes are used to improve the speed of data retrieval operations on a table.

OptionExampleDescription
CREATE INDEXCREATE INDEX idx_name ON users(name);Create an index on the name column.
UNIQUE INDEXCREATE UNIQUE INDEX idx_email ON employees(email);Ensure all indexed values are unique.
REINDEXREINDEX TABLE employees;Rebuild corrupted or outdated indexes.
DROP INDEXDROP INDEX idx_name;Delete an index.

Constraints #

Constraints enforce data integrity rules at the database level, ensuring accuracy and reliability.

OptionExampleDescription
PRIMARY KEYid SERIAL PRIMARY KEYUniquely identify each record in a table.
FOREIGN KEYFOREIGN KEY (dept_id) REFERENCES departments(id)Establish a relationship between two tables.
UNIQUEemail TEXT UNIQUEEnsure all values in a column are unique.
NOT NULLname TEXT NOT NULLEnsure the column cannot contain NULL values.
CHECKsalary NUMERIC CHECK (salary > 0)Enforce a condition for valid data.
DEFAULTjoined TIMESTAMP DEFAULT CURRENT_TIMESTAMPSet a default value if none is provided.

Data Manipulation Language (DML) #

DML commands are used for managing data within table objects, including inserting, updating, and deleting records.

OptionExampleDescription
INSERTINSERT INTO users (name) VALUES ('Alice');Add a new row to the table.
UPDATEUPDATE users SET name = 'Bob' WHERE id = 1;Modify existing rows.
DELETEDELETE FROM users WHERE id = 1;Remove rows from a table matching a condition.
RETURNINGINSERT INTO users (name) VALUES ('Dan') RETURNING id;Return values after insert, update, or delete.
ON CONFLICTINSERT INTO users (id, email) VALUES (1, 'a@b.com') ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email;Insert or update on conflict (upsert).

Joins #

Joins combine rows from two or more tables based on a related column between them.

OptionExampleDescription
INNER JOINSELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id;Return only matching rows.
LEFT JOINSELECT * FROM orders LEFT JOIN customers ON orders.customer_id = customers.id;Return all rows from the left table and matched rows from the right.
RIGHT JOINSELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.id;Return all rows from the right table and matched rows from the left.
FULL JOINSELECT * FROM orders FULL JOIN customers ON orders.customer_id = customers.id;Return all matched and unmatched rows from both tables.
CROSS JOINSELECT e.name, d.name FROM employees e CROSS JOIN departments d;Return Cartesian product of two tables.
SELF JOINSELECT a.name, b.manager FROM employees a JOIN employees b ON a.id = b.manager_id;Join a table to itself.

Aggregation and grouping #

Aggregate functions perform a calculation on a set of rows and return a single value, often used with GROUP BY.

OptionExampleDescription
COUNT()SELECT COUNT(*) FROM users;Count number of rows.
SUM()SELECT SUM(price) FROM products;Calculate total sum.
AVG()SELECT AVG(age) FROM users;Calculate average value.
MIN()SELECT MIN(salary) FROM employees;Return the smallest value.
MAX()SELECT MAX(salary) FROM employees;Return the largest value.
STRING_AGG()SELECT department, STRING_AGG(name, ', ') FROM employees GROUP BY department;Concatenate strings from a group into a single string.
GROUP BYSELECT department, COUNT(*) FROM employees GROUP BY department;Group results by column and apply aggregation.
HAVINGSELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;Filter grouped results.

Common table expressions (CTEs) #

CTEs create temporary result sets that can be referenced within a larger query, improving readability and enabling recursion.

OptionExampleDescription
WITHWITH regional_sales AS (SELECT region, SUM(amount) FROM orders GROUP BY region) SELECT * FROM regional_sales;Define a CTE for use in the main query.

Window functions #

Window functions perform calculations across a set of table rows that are somehow related to the current row.

OptionExampleDescription
OVER()SELECT name, salary, RANK() OVER (ORDER BY salary DESC) FROM employees;Define the window for the function to operate on.
ROW_NUMBER()SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)Assign a unique sequential integer to rows within a partition.
LAG() / LEAD()SELECT sales, LAG(sales) OVER (ORDER BY date) FROM daily_sales;Access data from a previous or subsequent row.

Transactions #

Transactions group a set of database tasks into a single unit of work that is either fully completed or fully rolled back.

OptionExampleDescription
BEGINBEGIN;Start a transaction block.
COMMITCOMMIT;Save all changes made during the transaction.
ROLLBACKROLLBACK;Undo all changes since the transaction began.
SAVEPOINTSAVEPOINT my_save;Set a savepoint within a transaction to allow partial rollback.
ROLLBACK TO SAVEPOINTROLLBACK TO SAVEPOINT my_save;Roll back to a specific savepoint.

psql Meta-commands #

These are special commands for the psql client that provide information about the database and control the client’s behavior.

OptionExampleDescription
\dt\dtList all tables in the current database.
\d tablename\d usersShow schema/structure of a table.
\du\duList all roles.
\dn\dnList all schemas.
\x\xToggle expanded output.
\timing\timingToggle timing of queries.
\i filename\i my_script.sqlExecute SQL commands from a file.
\?\?Show help for psql meta-commands.

User roles and permissions #

These commands manage database access control, defining users, roles, and their privileges on various objects.

OptionExampleDescription
CREATE USERCREATE USER alice WITH PASSWORD 'password';Create a new database user.
GRANTGRANT SELECT ON employees TO alice;Grant privileges to a user.
REVOKEREVOKE INSERT ON employees FROM alice;Remove privileges from a user.
ALTER ROLEALTER ROLE alice CREATEDB;Modify a user’s attributes.
ALTER USERALTER USER john WITH SUPERUSER;Modify an existing user’s privileges.
DROP USERDROP USER john;Delete a user account.

Import and export #

These utilities are essential for moving data into and out of your PostgreSQL database.

OptionExampleDescription
\copy\copy users FROM 'data.csv' CSV HEADER;Import data from a CSV file (client-side).
\copy\copy users TO 'output.csv' CSV HEADER;Export table to a CSV file (client-side).
COPYCOPY users FROM '/path/data.csv' CSV HEADER;Import data from a CSV file (server-side, superuser).
pg_dumppg_dump -U john -d inventory > dump.sqlExport database to a SQL file.
psqlpsql -U john -d inventory < dump.sqlRestore a database from a dump file.

Data types #

PostgreSQL supports a rich set of data types to store various kinds of information.

Type CategoryExample Data TypeDescription
NumericINTEGER, NUMERIC, SERIAL, BIGINTStore numbers, with or without decimals.
CharacterCHAR(n), VARCHAR(n), TEXTStore fixed or variable-length text strings.
Date/TimeDATE, TIME, TIMESTAMP, INTERVALStore date and time information.
BooleanBOOLEANStore logical TRUE or FALSE values.
JSON/XMLJSON, JSONB, XMLStore structured or semi-structured data.
ArrayINTEGER[], TEXT[]Store arrays of elements of the same type.
UUIDUUIDStore Universally Unique Identifiers.
SpatialGEOMETRY, GEOGRAPHYStore geometric and geographic data (via PostGIS).
Full-Text SearchTSVECTOR, TSQUERYStore and query optimized text for full-text search.

Getting help #

This section covers commands to access documentation and help directly within the psql command-line interface.

OptionExampleDescription
\h\hGet help on the syntax of SQL commands.
\h COMMAND\h DELETEGet detailed syntax help for a specific SQL command (e.g., DELETE).
\?\?List all available psql meta-commands.

FAQ's #

Most common questions and brief, easy-to-understand answers on the topic:

How do you connect to a PostgreSQL database using the command line?

Use psql -U username -d database_name to connect to a PostgreSQL database via the terminal.

What is the difference between WHERE and HAVING in SQL?

WHERE filters rows before grouping, while HAVING filters groups after aggregation.

How do you list all tables in a PostgreSQL database?

Use \dt inside psql to list all tables.

How do you check your PostgreSQL version?

Use SELECT version(); or run psql --version in the terminal.

How do you export a PostgreSQL table to a CSV file?

Use \copy tablename TO 'file.csv' CSV HEADER; inside psql.

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

PostgreSQL cheat sheet by Jonas Jared Jacek is licensed under CC BY-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/postgresql-cheat-sheet">PostgreSQL cheat sheet</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>

For more information see the Ditig legal page.

All Topics

Random Quote

“Content precedes design. Design in the absence of content is not design, it's decoration.”

 Jeffery Zeldman American web designer, author, and advocate for web standardsTwitter, - IT quotes