SQL Cheat Sheet

Updated · 4 min read
easyPostgreSQL 18sqlcheat-sheetreferenceassessment

The SQL you'll write most, on one page. Examples use the Fee Tracker and PostgreSQL; the standard forms work almost everywhere, and the SQL Syntax by Database has the spelling for other databases. Print it (Ctrl+P or Cmd+P) or keep it open in a tab.

Query

SQL
SELECT DISTINCT city, state           -- columns (DISTINCT drops duplicate rows)
FROM students AS s                    -- table, with an alias
WHERE grade >= 10 AND email IS NULL   -- filter rows
ORDER BY city, state                  -- sort (add DESC for descending)
LIMIT 10 OFFSET 20;                   -- page (standard: FETCH FIRST 10 ROWS ONLY)
FilterExample
Comparefee_usd > 400, state <> 'CA'
Range, inclusivefee_usd BETWEEN 200 AND 450
Liststate IN ('CA', 'TX')
Patterntitle LIKE 'Java%' (% any, _ one character)
Missing valueemail IS NULL (never = NULL)
CombineAND, OR, NOT; parentheses when mixing

Join

SQL
SELECT s.first_name, c.title
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id        -- matching rows only
LEFT JOIN payments AS p ON p.student_id = e.student_id
                       AND p.course_id = e.course_id     -- keep every enrollment
JOIN courses AS c ON c.course_id = e.course_id;
JoinKeeps
JOIN / INNER JOINRows with a match on both sides
LEFT JOINEvery row on the left, NULLs where nothing matches
FULL JOINEvery row from both sides
CROSS JOINEvery combination
Anti-joinWHERE NOT EXISTS (SELECT 1 FROM ... WHERE ...)

Group

SQL
SELECT technology, count(*) AS courses, avg(fee_usd) AS avg_fee
FROM courses
WHERE level = 'Beginner'          -- filter rows first
GROUP BY technology
HAVING count(*) > 1               -- then filter groups
ORDER BY avg_fee DESC;

Aggregates: count(*) (rows), count(col) (non-NULL values), count(DISTINCT col), sum, avg, min, max, string_agg(col, ', '). Subtotals: GROUP BY ROLLUP (a, b). Conditional: count(*) FILTER (WHERE method = 'card').

Change Data

SQL
INSERT INTO courses (title, technology, level, fee_usd)
VALUES ('Git Advanced', 'Git', 'Intermediate', 300.00)
RETURNING course_id;
 
UPDATE courses SET fee_usd = fee_usd * 1.05 WHERE technology = 'Java';
DELETE FROM payments WHERE payment_id = 7;
 
INSERT INTO courses (course_id, title, technology, level, fee_usd)   -- upsert
VALUES (6, 'Git Basics', 'Git', 'Beginner', 175.00)
ON CONFLICT (course_id) DO UPDATE SET fee_usd = EXCLUDED.fee_usd;

Create

SQL
CREATE TABLE study_sessions (
  session_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL REFERENCES students (student_id),
  studied_on DATE    NOT NULL DEFAULT CURRENT_DATE,
  minutes    INTEGER NOT NULL CHECK (minutes > 0),
  topic      VARCHAR(60)
);
CREATE INDEX study_sessions_student_idx ON study_sessions (student_id);
ALTER TABLE study_sessions ADD COLUMN notes TEXT;
CREATE VIEW recent_sessions AS SELECT * FROM study_sessions WHERE studied_on >= DATE '2026-01-01';

Types: INTEGER, BIGINT, NUMERIC(8,2) (money), VARCHAR(n), TEXT, BOOLEAN, DATE, TIMESTAMPTZ, JSONB.

Functions

NeedExample
Textlower(s), upper(s), trim(s), length(s), a || b, replace(s, a, b), substring(s FROM 1 FOR 3)
Numbersround(x, 2), ceil(x), floor(x), abs(x), x / NULLIF(y, 0)
DatesCURRENT_DATE, d + 30, d2 - d1, EXTRACT(YEAR FROM d), date_trunc('month', d)
NULLsCOALESCE(a, b), NULLIF(a, b)
ConditionsCASE WHEN fee_usd > 400 THEN 'high' ELSE 'standard' END
TypesCAST(x AS NUMERIC) (PostgreSQL also x::numeric)

Subqueries and CTEs

SQL
WITH totals AS (                                  -- name a step
  SELECT student_id, sum(amount_usd) AS paid_usd
  FROM payments GROUP BY student_id
)
SELECT s.first_name, t.paid_usd
FROM students s
JOIN totals t ON t.student_id = s.student_id
WHERE t.paid_usd > (SELECT avg(paid_usd) FROM totals);   -- scalar subquery

Window Functions

SQL
SELECT student_id, paid_on, amount_usd,
       ROW_NUMBER() OVER (PARTITION BY student_id ORDER BY paid_on) AS nth,
       sum(amount_usd) OVER (PARTITION BY student_id ORDER BY paid_on) AS running_usd,
       lag(amount_usd) OVER (PARTITION BY student_id ORDER BY paid_on) AS previous_usd,
       RANK() OVER (ORDER BY amount_usd DESC) AS size_rank
FROM payments;

Transactions

SQL
BEGIN;
UPDATE courses SET fee_usd = fee_usd + 10 WHERE course_id = 1;
SAVEPOINT step_one;
UPDATE courses SET fee_usd = 1.00 WHERE course_id = 2;  -- oops
ROLLBACK TO SAVEPOINT step_one;
COMMIT;                                                  -- or ROLLBACK to undo all

Performance and Safety

DoWhy
EXPLAIN (ANALYZE) SELECT ...See the real plan and rows read
Index columns you filter and join onFind rows without reading the table
WHERE d >= '2025-01-01' AND d < '2026-01-01'Ranges on bare columns can use indexes
Keyset paging: WHERE id > :last ORDER BY id LIMIT 20Deep pages stay fast
Parameters ($1, %s, ?) in app codePrevents SQL injection
A limited role for the appLimits damage from bugs and attacks

Try It

Every pattern above works on the Fee Tracker. Here are a few at once:

SQL▶ Try it
SELECT c.technology,
       count(p.payment_id)                         AS payments,
       coalesce(sum(p.amount_usd), 0)              AS collected_usd,
       RANK() OVER (ORDER BY coalesce(sum(p.amount_usd), 0) DESC) AS rank
FROM courses c
LEFT JOIN payments p ON p.course_id = c.course_id
GROUP BY c.technology
ORDER BY rank, c.technology;
Output
 technology | payments | collected_usd | rank
------------+----------+---------------+------
 Java       |        4 |       1500.00 |    1
 JavaScript |        2 |        450.00 |    2
 SQL        |        1 |        200.00 |    3
 Git        |        0 |             0 |    4
(4 rows)

Was this tutorial helpful?