PostgreSQL cheat sheet
Everyday Postgres in PostgreSQL's own syntax, including the shortcuts other engines make you work around: RETURNING, ON CONFLICT, :: casts and FILTER.
sqlly.app/sql-cheat-sheets/postgresql
SELECT basics
- Everything from a table
SELECT * FROM customers;- First 10 rows, ordered
SELECT * FROM customers ORDER BY last_name LIMIT 10;- Expression with an alias and a cast
SELECT first_name || ' ' || last_name AS full_name, created_at::date FROM customers;- Unique values
SELECT DISTINCT country FROM customers;- First row per group
SELECT DISTINCT ON (customer_id) customer_id, placed_at FROM orders ORDER BY customer_id, placed_at DESC;
Jointures
- Inner join
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;- Left join keeps unmatched rows
SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;- Both sides, matched or not
SELECT e.name, m.name FROM employees e FULL OUTER JOIN managers m ON m.employee_id = e.id;- Join on equal column names with USING
SELECT i.order_id, s.shipped_at FROM order_items i JOIN shipments s USING (order_id);- Lateral join per row
SELECT c.name, recent.placed_at FROM customers c CROSS JOIN LATERAL (SELECT placed_at FROM orders o WHERE o.customer_id = c.id ORDER BY placed_at DESC LIMIT 3) recent;
Filtrage
- Combined conditions
SELECT * FROM orders WHERE country = 'DE' AND placed_at >= '2026-01-01';- Case-insensitive pattern match
SELECT * FROM customers WHERE name ILIKE 'ada%';- Range and lists
SELECT * FROM orders WHERE total BETWEEN 100 AND 500 AND status IN ('new', 'paid');- Exists elsewhere
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);- Array membership
SELECT * FROM orders WHERE 'vip' = ANY (tags);
Aggregation
- Count per group
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;- Groups after filtering with HAVING
SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id HAVING SUM(total) > 1000;- Conditional aggregates with FILTER
SELECT department, COUNT(*) FILTER (WHERE active) AS active_count FROM employees GROUP BY department;- Rank within a partition
SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;- Aggregate text with string_agg
SELECT country, string_agg(name, ', ' ORDER BY name) FROM customers GROUP BY country;
Insert, update, delete
- Insert and read back the key
INSERT INTO customers (first_name, last_name) VALUES ('Ada', 'Lovelace') RETURNING id;- Upsert with ON CONFLICT
INSERT INTO stock (sku, count) VALUES ('A1', 5) ON CONFLICT (sku) DO UPDATE SET count = stock.count + EXCLUDED.count;- Insert or do nothing
INSERT INTO subscribers (email) VALUES ('[email protected]') ON CONFLICT (email) DO NOTHING;- Update from another table
UPDATE products p SET price = s.price FROM supplies s WHERE s.sku = p.sku;- Delete with a join via USING
DELETE FROM orders o USING customers c WHERE o.customer_id = c.id AND c.closed;
Create, alter, drop
- Create a table
CREATE TABLE orders (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers (id), total NUMERIC(10,2) NOT NULL DEFAULT 0, placed_at TIMESTAMPTZ NOT NULL DEFAULT now());- Add a column
ALTER TABLE customers ADD COLUMN tier text NOT NULL DEFAULT 'standard';- Rename a column
ALTER TABLE customers RENAME COLUMN name TO full_name;- Drop if it exists
DROP TABLE IF EXISTS temp_results;
Index
- Index a join key
CREATE INDEX idx_orders_customer_id ON orders (customer_id);- Partial index
CREATE INDEX idx_orders_open ON orders (customer_id) WHERE status = 'open';- Expression index
CREATE INDEX idx_customers_email ON customers (lower(email));- GIN index for JSONB
CREATE INDEX idx_events_payload ON events USING GIN (payload jsonb_path_ops);- Build without blocking writes
CREATE INDEX CONCURRENTLY idx_orders_placed ON orders (placed_at);
String functions
- Length and case
SELECT length(name), lower(email), upper(code) FROM customers;- Substring and position
SELECT substring(name FROM 1 FOR 3), position('@' IN email) FROM customers;- Split on a delimiter
SELECT split_part(path, '/', 2) FROM links;- Match a regular expression
SELECT substring(code FROM '^[0-9]+') FROM items;- Trim and replace
SELECT trim(name), replace(code, '-', '') FROM customers;
Date functions
- En ce moment
SELECT now();- Intervals
SELECT now() - interval '7 days';- Recent rows
SELECT * FROM orders WHERE placed_at >= now() - interval '30 days';- Truncate to a month
SELECT date_trunc('month', placed_at) AS month, sum(total) FROM orders GROUP BY 1;- Format a timestamp
SELECT to_char(placed_at, 'YYYY-MM-DD') FROM orders;
NULL handling
- Substitute a default
SELECT coalesce(nickname, first_name, 'unknown') FROM customers;- Guard a division by zero
SELECT total / NULLIF(quantity, 0) FROM orders;- Test for NULL
SELECT * FROM customers WHERE deleted_at IS NULL;- Compare two columns, treating NULLs as equal
SELECT * FROM products p JOIN supplies s ON s.sku = p.sku WHERE p.price IS DISTINCT FROM s.price;
Paging
- Page 3, 10 rows per page
SELECT * FROM orders ORDER BY placed_at DESC LIMIT 10 OFFSET 20;- Fast keyset paging
SELECT * FROM orders WHERE (placed_at, id) < ('2026-01-01', 123) ORDER BY placed_at DESC, id DESC LIMIT 10;
PostgreSQL quirks worth knowing
- Unquoted names fold to lowercase.
MyTabledevientmytable; to keep mixed case you must quote it as"MyTable"forever. Double quotes are identifiers; single quotes are strings. - INSERT can give the row back.
RETURNING id(ouRETURNING *) returns the inserted or updated rows, so no second round-trip for generated keys. - Upserts are ON CONFLICT.
INSERT … ON CONFLICT (sku) DO UPDATE SET …avecEXCLUDEDfor the rejected row's values. - Casts are two colons.
created_at::date,'7'::int; andILIKEis the case-insensitiveLIKE. - Aggregates take a FILTER.
COUNT(*) FILTER (WHERE active)replaces the conditional CASE inside every aggregate.
Other SQL cheat sheets
To run this sheet against a live database, get the SQLly desktop app for PostgreSQL, ou parcourez toutes les fonctionnalités.
Related on SQLly
PostgreSQL cheat sheet FAQ
How do I limit rows in PostgreSQL?
Append LIMIT 10, and OFFSET 20 to skip rows. There is no TOP clause; that is SQL Server syntax.
How do I get the ID of the row I just inserted?
Add RETURNING id (or RETURNING *) to the INSERT. It hands back the generated values without a second query. UPDATE and DELETE accept RETURNING too, and PostgreSQL 18 lets RETURNING name old.* and new.* to see the row before and after the change.
Why is my table not found even though I created it?
PostgreSQL folds unquoted names to lowercase. If you created "MyTable" with double quotes, you must always quote it; otherwise PostgreSQL looks for mytable. Prefer lowercase names and you never need quotes.
Should I use SERIAL or GENERATED ALWAYS AS IDENTITY?
Prefer GENERATED ALWAYS AS IDENTITY (or BY DEFAULT when you must insert explicit values). It is the SQL standard form; SERIAL is the older shorthand that ties the column to a sequence you can accidentally desynchronize.
Run these against your own database
SQLly is a native SQL workbench for macOS, Windows and Linux. It connects to all five engines on these sheets, and its IntelliSense completes from your real schema.