UtilityBelt
Back to Cheatsheets

SQL Cheatsheet

Essential SQL commands for daily CRUD operations — queries, joins, aggregations, and more.

SELECT Queries

The SELECT statement retrieves rows from a table. Every CRUD developer reaches for it dozens of times a day.

Basic SELECT

SELECT id, name, email FROM users;

SELECT with WHERE

SELECT * FROM orders WHERE status = 'pending' AND created_at >= '2025-01-01';

SELECT with JOIN

SELECT u.name, o.total, o.created_at FROM users u JOIN orders o ON o.user_id = u.id WHERE u.active = true;

GROUP BY & Aggregation

SELECT status, COUNT(*) AS count, SUM(total) AS revenue FROM orders GROUP BY status;

ORDER BY

SELECT id, title, created_at FROM posts ORDER BY created_at DESC LIMIT 10 OFFSET 0;

HAVING (filter after aggregation)

SELECT user_id, COUNT(*) AS order_count FROM orders GROUP BY user_id HAVING COUNT(*) > 5 ORDER BY order_count DESC;

Subqueries

SELECT name, email FROM users WHERE id IN ( SELECT user_id FROM orders WHERE total > 1000 );
INSERT / UPDATE / DELETE

The core CRUD triad. Modern PostgreSQL supports the RETURNING clause, saving you a follow-up SELECT.

INSERT

INSERT INTO users (name, email, role) VALUES ('Alice', 'alice@example.com', 'admin');

INSERT with RETURNING

INSERT INTO users (name, email, role) VALUES ('Bob', 'bob@example.com', 'editor') RETURNING id, created_at;

INSERT multiple rows

INSERT INTO tags (name, slug) VALUES ('JavaScript', 'javascript'), ('React', 'react'), ('PostgreSQL', 'postgresql') RETURNING *;

INSERT … ON CONFLICT (upsert)

INSERT INTO users (email, name, login_count) VALUES ('alice@example.com', 'Alice', 1) ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name, login_count = users.login_count + 1, updated_at = NOW() RETURNING *;

UPDATE

UPDATE users SET role = 'moderator', updated_at = NOW() WHERE email = 'bob@example.com' RETURNING id, name, role;

DELETE

DELETE FROM sessions WHERE expires_at < NOW() RETURNING id, user_id;

DELETE with JOIN (using USING)

DELETE FROM orders o USING users u WHERE o.user_id = u.id AND u.active = false RETURNING o.id;
Table Operations

DDL statements for creating, altering, and dropping tables, plus the most useful column constraints.

CREATE TABLE

CREATE TABLE posts ( id          SERIAL PRIMARY KEY, title       VARCHAR(255) NOT NULL, slug        VARCHAR(255) UNIQUE NOT NULL, body        TEXT, author_id   INTEGER NOT NULL REFERENCES users(id), status      VARCHAR(20) NOT NULL DEFAULT 'draft' CHECK (status IN ('draft','published','archived')), created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW() );

ALTER TABLE — add column

ALTER TABLE posts ADD COLUMN excerpt VARCHAR(300);

ALTER TABLE — add constraint

ALTER TABLE comments ADD CONSTRAINT fk_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE;

DROP TABLE

DROP TABLE IF EXISTS temp_imports CASCADE;

Constraints reference

-- Primary key id  SERIAL PRIMARY KEY -- Foreign key author_id  INTEGER REFERENCES authors(id) ON DELETE CASCADE -- Unique email  VARCHAR(255) UNIQUE NOT NULL -- Not null name   VARCHAR(100) NOT NULL -- Check age    INTEGER CHECK (age >= 0 AND age <= 150) -- Default created_at  TIMESTAMPTZ DEFAULT NOW()
Aggregation Functions

Aggregate functions collapse many rows into a single result, usually paired with GROUP BY.

SELECT COUNT(*)                    AS total_orders, COUNT(DISTINCT user_id)     AS unique_customers, SUM(total)                  AS revenue, AVG(total)                  AS avg_order_value, MIN(total)                  AS smallest_order, MAX(total)                  AS largest_order FROM orders WHERE created_at >= NOW() - INTERVAL '30 days';

Aggregation by group

SELECT category, COUNT(*)           AS product_count, AVG(price)         AS avg_price, MIN(price)         AS min_price, MAX(price)         AS max_price FROM products GROUP BY category ORDER BY product_count DESC;

GROUP_CONCAT (string_agg in PostgreSQL)

SELECT o.id, STRING_AGG(p.name, ', ' ORDER BY p.name) AS products FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p    ON p.id = oi.product_id GROUP BY o.id;
Joins

Joins combine rows from two or more tables based on a related column. Knowing when to use each type is essential for writing efficient queries.

INNER JOIN

SELECT u.name, o.total FROM users u INNER JOIN orders o ON o.user_id = u.id; -- Only rows where match exists in BOTH tables

LEFT JOIN

SELECT u.name, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id, u.name; -- ALL rows from users, NULLs for users with no orders

RIGHT JOIN

SELECT p.title, c.body AS comment FROM posts p RIGHT JOIN comments c ON c.post_id = p.id; -- ALL rows from comments, NULLs for comments with no post

FULL OUTER JOIN

SELECT COALESCE(u.name, '(deleted)') AS user_name, o.total FROM users u FULL OUTER JOIN orders o ON o.user_id = u.id; -- ALL rows from BOTH tables, NULLs where no match

CROSS JOIN

SELECT sizes.name, colors.name FROM sizes CROSS JOIN colors; -- Cartesian product: every size × every color

SELF JOIN

SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON m.id = e.manager_id; -- Table joined to itself to represent hierarchies
Window Functions

Window functions perform calculations across a set of rows related to the current row — without collapsing them like GROUP BY.

ROW_NUMBER

SELECT id, title, created_at, ROW_NUMBER() OVER (ORDER BY created_at DESC) AS row_num FROM posts;

RANK & DENSE_RANK

SELECT name, score, RANK()       OVER (ORDER BY score DESC) AS rank, DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank FROM leaderboard; -- RANK skips positions on ties (1,1,3), DENSE_RANK doesn't (1,1,2)

LAG & LEAD

SELECT date, amount, LAG(amount, 1)  OVER (ORDER BY date) AS prev_day, LEAD(amount, 1) OVER (ORDER BY date) AS next_day, amount - LAG(amount, 1) OVER (ORDER BY date) AS day_over_day_change FROM daily_revenue;

SUM() OVER (running total)

SELECT date, amount, SUM(amount) OVER (ORDER BY date) AS running_total FROM daily_revenue;

Window with PARTITION BY

SELECT department, name, salary, AVG(salary) OVER (PARTITION BY department) AS dept_avg, salary - AVG(salary) OVER (PARTITION BY department) AS diff_from_avg FROM employees;
Common Table Expressions (CTEs)

CTEs (the WITH clause) let you name a subquery and reuse it in the main query — great for readability and recursive queries.

Simple CTE

WITH active_users AS ( SELECT id, name, email FROM users WHERE active = true AND last_login > NOW() - INTERVAL '90 days' ) SELECT a.name, o.total FROM active_users a JOIN orders o ON o.user_id = a.id WHERE o.total > 50;

Multiple CTEs

WITH recent_orders AS ( SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL '7 days' ), order_stats AS ( SELECT user_id, COUNT(*) AS cnt, SUM(total) AS total_spent FROM recent_orders GROUP BY user_id ) SELECT u.name, COALESCE(os.cnt, 0) AS orders_7d, COALESCE(os.total_spent, 0) AS spent_7d FROM users u LEFT JOIN order_stats os ON os.user_id = u.id ORDER BY spent_7d DESC NULLS LAST;

Recursive CTE (hierarchy)

WITH RECURSIVE org_tree AS ( -- Anchor: top-level managers SELECT id, name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL -- Recursive: direct reports SELECT e.id, e.name, e.manager_id, ot.level + 1 FROM employees e JOIN org_tree ot ON ot.id = e.manager_id ) SELECT * FROM org_tree ORDER BY level, name;
Indexes

Indexes speed up lookups at the cost of slower writes. The right index can turn a 10-second scan into a millisecond seek.

Basic index

CREATE INDEX idx_posts_author_id ON posts(author_id);

UNIQUE index

CREATE UNIQUE INDEX idx_users_email ON users(email);

Composite index

CREATE INDEX idx_orders_user_status ON orders(user_id, status); -- Use when filtering by both user_id AND status

Partial index

CREATE INDEX idx_orders_pending ON orders(created_at) WHERE status = 'pending'; -- Only indexes rows where status = 'pending'

Covering index (INCLUDE)

CREATE INDEX idx_posts_author_covering ON posts(author_id) INCLUDE (title, created_at); -- Index-only scan: no need to visit table heap

Drop index

DROP INDEX IF EXISTS idx_old_unused_index;
Transactions

Transactions group multiple operations into a single atomic unit — all succeed or all roll back. Essential for data integrity in any CRUD application.

Basic transaction

BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- Both updates succeed together, or neither does

Transaction with ROLLBACK

BEGIN; INSERT INTO orders (user_id, total) VALUES (1, 50.00); -- Oops, something went wrong — undo everything ROLLBACK;

SAVEPOINT (nested rollback)

BEGIN; INSERT INTO audit_log (action) VALUES ('batch_start'); SAVEPOINT before_insert; INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com'); -- Something wrong with Charlie, roll back just that insert ROLLBACK TO SAVEPOINT before_insert; INSERT INTO users (name, email) VALUES ('Diana', 'diana@example.com'); COMMIT; -- Charlie is NOT inserted; Diana IS; audit log saved

Transaction with error handling (PL/pgSQL)

DO $$ BEGIN BEGIN INSERT INTO users (email, name) VALUES ('alice@example.com', 'Alice'); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'User already exists, skipping'; END; END $$;
PostgreSQL Specific Features

PostgreSQL offers powerful data types and operators not found in standard SQL — especially for JSON, arrays, and set generation.

JSON operators — access fields

SELECT metadata->'author'    AS author_json,    -- returns JSON metadata->>'title'    AS title_text,     -- returns TEXT metadata->'tags'      AS tags_json,      -- returns JSON array metadata->'address'->>'city' AS city     -- nested path FROM articles WHERE metadata @> '{"published": true}';    -- JSON containment check

JSON path queries (PostgreSQL 12+)

-- Find articles where any tag starts with "react" SELECT id, metadata->>'title' AS title FROM articles WHERE metadata @@ '$.tags[*] like_regex "react" flag "i"';

JSON_QUERY / JSON_VALUE (SQL/JSON)

-- PostgreSQL 15+ SQL/JSON standard functions SELECT JSON_VALUE(metadata, '$.title')       AS title, JSON_QUERY(metadata, '$.tags')        AS tags, JSON_VALUE(metadata, '$.price' RETURNING NUMERIC) AS price FROM products WHERE JSON_VALUE(metadata, '$.active')::boolean = true;

ARRAY type & operations

-- Create table with array column CREATE TABLE articles ( id    SERIAL PRIMARY KEY, title TEXT NOT NULL, tags  TEXT[]              -- array of text ); -- Query with array operators SELECT id, title FROM articles WHERE tags @> ARRAY['react'];              -- contains 'react' WHERE tags && ARRAY['react','vue'];         -- overlaps (any match) WHERE 'react' = ANY(tags);                  -- exact membership -- Array indexing (1-based in SQL) SELECT title, tags[1] AS primary_tag FROM articles;

UNNEST — expand arrays to rows

-- Flatten array into one row per element SELECT a.id, a.title, UNNEST(a.tags) AS single_tag FROM articles a; -- With ordinality (preserves position) SELECT a.id, t.tag, t.ordinality AS position FROM articles a, LATERAL UNNEST(a.tags) WITH ORDINALITY AS t(tag);

GENERATE_SERIES — create row sets

-- Generate a sequence of numbers SELECT GENERATE_SERIES(1, 10) AS num; -- Generate a calendar (super useful for reporting) SELECT d::DATE AS date FROM GENERATE_SERIES( '2025-01-01'::DATE, '2025-01-31'::DATE, '1 day'::INTERVAL ) AS d; -- Cartesian product with real data SELECT d.date, COALESCE(SUM(o.total), 0) AS daily_revenue FROM GENERATE_SERIES( '2025-01-01'::DATE, '2025-01-31'::DATE, '1 day' ) AS d LEFT JOIN orders o ON o.created_at::DATE = d.date GROUP BY d.date ORDER BY d.date;