Skip to main content
Quick Reference

PostgreSQL Cheatsheet

PostgreSQL on one page — identity columns, LIMIT, joins, grouping, indexes, transactions, and the traps around NULL, case, and RETURNING.

10 sections 10 tables 14 code snippets

Connect

psql

psql -h localhost -U app -d shop

Look around

\dt
\d books

The names

NameMeaning
DatabaseChosen with -d shop. \c shop switches later. There is no USE
Schemapublic is the usual default. An unqualified name follows search_path
Port 5432The default. The server asks for the password. Do not put it on the command line
SemicolonSends the SQL statement
\dA psql command. It runs at once and does not take a semicolon
Unquoted namesFold to lowercase. A quoted name keeps its case and must stay quoted

This page is SQL in psql. One statement outside an explicit transaction commits when it succeeds.

Create a table

Identity and exact money

CREATE TABLE books (
  id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  title text NOT NULL,
  pages int NOT NULL,
  price numeric(8, 2) NOT NULL,
  published timestamptz,
  CONSTRAINT pages_chk CHECK (pages > 0)
);

Column rules

PieceEffect
GENERATED BY DEFAULT AS IDENTITYFills id when you omit it. An explicit value is accepted
GENERATED ALWAYSRejects an explicit id unless the insert says OVERRIDING SYSTEM VALUE
Identity is not uniqueA primary key or a unique constraint still has to enforce that
textUnlimited characters. varchar(200) checks the length. Storage is the same
numeric(8, 2)Exact money. 8 is the total digits, 2 of them after the point
timestamptzStored in UTC and shown in the session time zone. Plain timestamp keeps the clock reading you typed

Insert

Several rows, and the new id

INSERT INTO books (title, pages, price)
VALUES
  ('Dune', 412, 18.50),
  ('Neuromancer', 271, 14.00)
RETURNING id;

What comes back

FormResult
RETURNING idThe identity values this statement created
Omitted idThe next identity value
Explicit id on BY DEFAULTStored as given. The sequence is not moved past it, so a later generated id can collide
ON CONFLICT (title) DO NOTHINGSkips a row that would break a unique constraint
ON CONFLICT DO UPDATEUpdates the existing row instead. Name the conflict target
Empty stringA real value. It is not NULL

Select

Ten rows after the sort

SELECT title, pages
FROM books
WHERE pages >= 300
ORDER BY pages DESC
LIMIT 10;

A later page

SELECT title, pages
FROM books
ORDER BY id
LIMIT 10 OFFSET 20;

SELECT now();

Read rules

FormMeaning
LIMIT 10Stops after 10 rows. Without ORDER BY those 10 are not defined
OFFSET 20Skips 20 rows. Put a unique column last in ORDER BY or rows can repeat and vanish across pages
SELECT now()Legal with no FROM
IS NULLThe null test. = NULL is never true
ILIKECase-insensitive match. Ordinary = treats Dune and dune as different
COALESCE(price, 0)A stand-in for NULL

Update & delete

Change a price

UPDATE books
SET price = 19
WHERE title = 'Dune';

Remove the short ones

DELETE FROM books
WHERE pages < 100;

Write rules

StatementTouches
UPDATE ... SETThe named columns on rows that pass WHERE. A successful statement commits
DELETE FROMWhole rows that pass WHERE. The table stays
No WHEREEvery row. psql will not ask you to confirm
RETURNINGThe rows just changed. Works on UPDATE and DELETE too
TRUNCATE booksEmpties the table. Add RESTART IDENTITY to reset the sequence
Inside BEGINThe change waits. See the transactions section

Joins

Orders with their book

SELECT o.id, b.title, o.amount
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id;

SELECT o.id, b.title
FROM orders AS o
LEFT JOIN books AS b ON b.id = o.book_id;

Which rows survive

JoinKeeps
INNER JOINOnly rows that match on both sides
LEFT JOINEvery left row. Missing right-side columns are NULL
ONThe match. A right-table filter in WHERE turns a left join into an inner join
AS oA short name. Required once both tables have id
WHERE b.id IS NULLLeft rows whose book is missing
ON DELETEThe default is NO ACTION. A parent delete fails while a child row points at it

Group & count

Revenue per book

SELECT b.id, b.title,
       COUNT(*) AS sold,
       SUM(o.amount) AS revenue
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id
GROUP BY b.id, b.title
HAVING SUM(o.amount) > 100
ORDER BY revenue DESC;

Aggregate rules

FormMeaning
COUNT(*)Rows in the group, including rows with NULL
COUNT(published)Rows where published is not NULL
SUM / AVGSkip NULL. AVG of no rows is NULL, not zero
GROUP BYEvery selected column that is not aggregated must be listed
HAVINGFilters groups. WHERE cannot see SUM
GROUP BY does not sortAdd ORDER BY when the order matters

Indexes & foreign keys

Index the column you look up

CREATE INDEX idx_books_title ON books (title);

ALTER TABLE orders
  ADD CONSTRAINT fk_orders_book
  FOREIGN KEY (book_id) REFERENCES books (id);

CREATE INDEX idx_orders_book ON orders (book_id);

What the planner uses

KeyDetail
Primary keyBuilds a unique index. That index enforces the key
(title, pages)Serves title, and title plus pages. Not pages alone
UNIQUERejects a second equal value. Several NULLs are allowed, unless you add NULLS NOT DISTINCT
Foreign keyDoes not create an index on book_id. Add that index yourself
A missing child indexA parent delete scans the child
EXPLAINShows the plan. Seq Scan reads the whole table. EXPLAIN ANALYZE runs the statement

Transactions

Two writes, one outcome

BEGIN;
UPDATE books SET price = price - 1 WHERE id = 1;
INSERT INTO orders (book_id, amount) VALUES (1, 17.50);
COMMIT;

When the work sticks

FactWhy it matters
AutocommitOn. One statement outside a transaction commits when it succeeds
BEGINHolds the following statements until COMMIT or ROLLBACK
DDLCREATE, ALTER, and DROP can sit inside the transaction and roll back with it
Identity and rollbackA consumed sequence value is not reused. Gaps are normal
TRUNCATE in a transactionCan roll back. RESTART IDENTITY also resets the sequence
CREATE INDEX CONCURRENTLYCannot run inside BEGIN. It builds the index without blocking writes

Interview traps

Traps worth memorising

TrapWhat happensPrefer
AUTO_INCREMENT or TOPNot PostgreSQLIDENTITY and LIMIT
LIMIT 10 with no ORDER BYAny 10 rowsAn ORDER BY that ends in a unique column
An empty titleA stored value. IS NULL does not find itIS NULL only when you mean NULL
title || NULLThe result is NULLconcat, which keeps the other part
WHERE title = NULLNever matchesIS NULL
Expecting Dune and dune to matchOrdinary = is case-sensitiveILIKE, or a case-insensitive collation
An explicit id on a BY DEFAULT identityStored, and the sequence stays behind. A later insert can collideOmit id, or advance the sequence after a manual value
UNIQUE and two NULLsBoth are allowedNULLS NOT DISTINCT when one NULL is the limit
A foreign key and no child indexParent deletes scan the childAn index on the referencing column
EXPLAIN ANALYZE on an updateThe update really runsEXPLAIN when you only want the plan
5 / 2 on integersThe result is 2A numeric cast when you want the fraction
timestamp for a zoned timeThe zone you typed is discardedtimestamptz

The page

ORDER BY id
LIMIT 10 OFFSET 20

The new id

RETURNING id

How to use this page: connect with psql, create books, and insert one title with RETURNING id. Then SELECT with ORDER BY and LIMIT, and wrap two writes in BEGIN before you COMMIT.