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 psql psql -h localhost -U app -d shop This page is SQL in psql. One statement outside an explicit transaction commits when it succeeds. 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)
); Several rows, and the new id INSERT INTO books (title, pages, price)
VALUES
('Dune', 412, 18.50),
('Neuromancer', 271, 14.00)
RETURNING id; 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(); Change a price UPDATE books
SET price = 19
WHERE title = 'Dune'; Remove the short ones DELETE FROM books
WHERE pages < 100; 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; 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; 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); 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; The page ORDER BY id
LIMIT 10 OFFSET 20 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. |