Skip to content

SQL and PostgreSQL cheat sheet

The SQL for queries, joins, grouping, constraints, indexes, transactions and EXPLAIN, plus the psql commands, that the Databases & SQL course uses, on one page.

psql

CommandWhat it does
psql -h host -U user dbnameconnect
\l / \c dblist databases / switch
\dt / \d tablelist tables / describe one
\di / \dvindexes / views
\xexpanded output for wide rows
\timingshow how long each query takes
\qquit

Querying

SELECT name, price_paise / 100.0 AS rupees
FROM products
WHERE category = 'dairy' AND price_paise < 10000
ORDER BY price_paise DESC
LIMIT 10;

IN (...), BETWEEN a AND b, LIKE 'pre%', IS NULL (never = NULL), DISTINCT.

Joins and grouping

SELECT s.name, count(o.id) AS orders, sum(o.total_paise) AS paise
FROM stores s
LEFT JOIN orders o ON o.store_id = s.id AND o.status = 'delivered'
GROUP BY s.name
HAVING count(o.id) > 0
ORDER BY orders DESC;

JOIN keeps matches only · LEFT JOIN keeps every left row · WHERE filters rows, HAVING filters groups · count(col) skips NULLs, count(*) does not.

Changing data

INSERT INTO stores (name, city, opened_on) VALUES ('Ludhiana Mall', 'Ludhiana', '2026-01-10') RETURNING id;
UPDATE stock SET quantity = quantity + 24 WHERE store_id = 1 AND product_id = 7;  -- a delivery arrived
DELETE FROM stock WHERE quantity = 0;

Run an UPDATE or DELETE as a SELECT with the same WHERE first.

Schema and constraints

CREATE TABLE bookings (
  id         serial PRIMARY KEY,
  room_id    integer NOT NULL REFERENCES rooms(id),
  starts_on  date NOT NULL,
  nights     integer NOT NULL CHECK (nights > 0),
  UNIQUE (room_id, starts_on)
);
ALTER TABLE bookings ADD COLUMN note text;

Indexes and EXPLAIN

EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
CREATE INDEX CONCURRENTLY ...;    -- on a live table

Seq Scan reads everything; Index Scan uses an index. A multi-column index helps queries on its leading columns.

Transactions

BEGIN;
  UPDATE ...;
  SAVEPOINT s1;
  UPDATE ...;
  ROLLBACK TO SAVEPOINT s1;
COMMIT;          -- or ROLLBACK;
SELECT ... FOR UPDATE;   -- lock the rows you read until COMMIT

After any error inside a transaction, only ROLLBACK works.

Try it in your browser

Practise it on a real machineDatabases & SQL Engineering course
Open the lab