Skip to main content

SQL Course

SQL Cheatsheet

A quick, printable reference with essential SQL syntax: SELECT, JOIN, GROUP BY, CTEs, window functions, DML, transactions, and common pitfalls. Print to PDF with Ctrl/Cmd + P.

PDF / Print

Save or print this cheatsheet as PDF

Print-ready layout: open in one click and save as PDF from your browser, no account or email required.

0. Core SQL Invariants & Pitfalls to Avoid

Check these five rules before running any query or write statement.

  1. Always test NULL with IS NULL / IS NOT NULL: comparing with = NULL or <> NULL yields UNKNOWN.
  2. Remember logical evaluation order: FROM/JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY -> LIMIT.
  3. Never use aggregate or window functions in WHERE: use HAVING for groups and a CTE/subquery for window results.
  4. Avoid NOT IN when a subquery can return NULL: prefer NOT EXISTS.
  5. Always preview UPDATE/DELETE targets with an equivalent SELECT first and wrap risky changes in BEGIN/ROLLBACK.

1. Basic SELECT

  • Simple read

    SELECT col1, col2 FROM table_name;
    SELECT * FROM table_name;

    Projects specific columns or every column in a table.

    Pitfall: Avoid SELECT * in production code: schema additions can silently break downstream consumers.

  • WHERE filter

    SELECT * FROM employees
    WHERE salary > 50000 AND city = 'Rome';

    Combines predicates with AND, OR, and NOT. String literals use single quotes.

    Pitfall: You cannot reference SELECT aliases inside WHERE because WHERE runs before SELECT.

  • Sorting

    SELECT * FROM products
    ORDER BY price DESC, name ASC;

    Sorts output rows by one or more expressions (ASC is default, DESC is descending).

    Pitfall: Without ORDER BY, relational engines make no guarantee about row ordering.

  • Pagination

    SELECT * FROM products
    ORDER BY id
    LIMIT 10 OFFSET 20;

    Returns a fixed slice of rows starting after OFFSET.

    Pitfall: LIMIT/OFFSET without a deterministic ORDER BY (such as a primary key) can skip or duplicate rows.

  • DISTINCT

    SELECT DISTINCT country FROM customers;

    Deduplicates rows across the selected column list.

    Pitfall: DISTINCT applies to the entire SELECT tuple, not just the first column.

  • Aliases

    SELECT first_name AS given_name, last_name AS family_name
    FROM employees AS e;

    Renames output columns and creates short table aliases for multi-table queries.

    Pitfall: In PostgreSQL, quoting aliases in double quotes makes them case-sensitive.

2. Aggregates and GROUP BY

  • Aggregate functions

    SELECT COUNT(*), AVG(price), SUM(stock),
           MAX(launched_on), MIN(price)
    FROM products;

    Computes summary statistics over all filtered rows.

    Pitfall: COUNT(*) counts every row, whereas COUNT(col) skips NULL values.

  • GROUP BY

    SELECT category_id, COUNT(*) AS item_count, AVG(price) AS avg_price
    FROM products
    GROUP BY category_id;

    Buckets rows by shared values and computes aggregates per group.

    Pitfall: Every non-aggregated column in SELECT must appear in GROUP BY.

  • HAVING

    SELECT category_id, COUNT(*) AS item_count
    FROM products
    GROUP BY category_id
    HAVING COUNT(*) >= 3;

    WHERE filters individual rows before grouping; HAVING filters groups after aggregation.

    Pitfall: Putting row-level conditions in HAVING instead of WHERE forces unnecessary grouping work.

3. JOINs and Set Operations

  • INNER JOIN

    SELECT o.id, c.first_name
    FROM orders AS o
    JOIN customers AS c ON c.id = o.customer_id;

    Keeps only rows that satisfy the join condition in both tables.

    Pitfall: Forgetting the ON clause produces a Cartesian product (CROSS JOIN).

  • LEFT / RIGHT / FULL OUTER

    SELECT c.first_name, o.id
    FROM customers AS c
    LEFT JOIN orders AS o ON o.customer_id = c.id;

    Preserves all left-side rows; unmatched right-side columns become NULL.

    Pitfall: Filtering a right-table column in WHERE turns a LEFT JOIN back into an INNER JOIN: move that condition into ON.

  • Multi-JOIN

    SELECT c.first_name, p.name, oi.quantity
    FROM customers AS c
    JOIN orders AS o       ON o.customer_id = c.id
    JOIN order_items AS oi ON oi.order_id   = o.id
    JOIN products AS p     ON p.id          = oi.product_id;

    Chains multiple tables along foreign-key relationships.

    Pitfall: Watch 1:N cardinality: summing parent-table amounts after joining a child table inflates totals.

  • Self-join

    SELECT c.name AS child_name, p.name AS parent_name
    FROM categories AS c
    JOIN categories AS p ON p.id = c.parent_id;

    Joins a table to itself using distinct aliases to traverse parent-child hierarchies.

    Pitfall: Omitting distinct aliases raises an ambiguous column reference error.

  • Set operations

    SELECT city FROM customers
    UNION
    SELECT city FROM employees;
    
    -- also: INTERSECT, EXCEPT, UNION ALL

    Stacks compatible result sets vertically with matching column counts and types.

    Pitfall: UNION performs a distinct sort step: use UNION ALL when duplicate removal is unnecessary.

4. Practical Syntax and NULL

  • IN / NOT IN

    WHERE country IN ('Italy', 'Spain');

    Tests set membership against a literal list or single-column subquery.

    Pitfall: If a subquery inside NOT IN yields even a single NULL, the query returns zero rows.

  • BETWEEN

    WHERE price BETWEEN 50 AND 200;

    Matches inclusive lower and upper bounds.

    Pitfall: With timestamps, BETWEEN "2026-01-01" AND "2026-01-31" misses rows after 00:00:00 on the 31st.

  • IS NULL / COALESCE

    WHERE shipped_at IS NULL;
    SELECT COALESCE(body, '(no text)') FROM reviews;

    Detects missing values and supplies a non-null fallback.

    Pitfall: Writing = NULL always evaluates to UNKNOWN in SQL three-valued logic.

  • CASE WHEN

    SELECT name,
      CASE
        WHEN price < 50  THEN 'budget'
        WHEN price < 200 THEN 'mid'
        ELSE 'premium'
      END AS price_tier
    FROM products;

    Computes conditional classifications row by row.

    Pitfall: Omitting ELSE makes unmatched rows evaluate to NULL.

  • Subqueries

    SELECT * FROM products
    WHERE price > (SELECT AVG(price) FROM products);

    Embeds a scalar or tabular query inside an outer expression.

    Pitfall: Scalar comparison operators (=, >) fail at runtime if the subquery returns multiple rows.

  • LIKE / ILIKE

    WHERE email LIKE '%@example.com'
       OR name ILIKE 'headphones%';

    Pattern matching using % (0+ chars) and _ (1 char). ILIKE is case-insensitive in PostgreSQL.

    Pitfall: Matching literal % or _ requires ESCAPE, and a leading % prevents standard B-Tree index scans.

5. Useful Functions

  • String

    LOWER(s), UPPER(s), LENGTH(s)
    CONCAT(a, ' ', b)   -- also  a || ' ' || b
    SUBSTRING(s FROM 1 FOR 3)
    TRIM(s), REPLACE(s, 'old', 'new')

    Standard text casing, slicing, trimming, and concatenation.

    Pitfall: Using || propagates NULL across the whole expression if any operand is NULL, whereas CONCAT skips NULL.

  • Numeric

    ROUND(x, 2), CEIL(x), FLOOR(x), ABS(x)
    MOD(a, b)  -- also  a % b

    Rounding modes, remainder, and absolute value.

    Pitfall: Integer division in PostgreSQL truncates toward zero (5 / 2 = 2); cast to NUMERIC for decimals.

  • Date and Time

    CURRENT_DATE, NOW()
    EXTRACT(YEAR  FROM ordered_at)
    EXTRACT(MONTH FROM ordered_at)
    DATE_TRUNC('month', ordered_at)
    ordered_at + INTERVAL '7 days'

    Extracts date parts, truncates timestamps to periods, and adds intervals.

    Pitfall: NOW() returns the transaction timestamp with time zone; avoid mixing timezone-aware and naive timestamps.

  • CAST

    CAST(price AS INTEGER)
    price::INTEGER       -- PostgreSQL shorthand

    Converts values explicitly between SQL data types.

    Pitfall: Use NUMERIC(10, 2) instead of FLOAT/REAL for monetary values to avoid binary rounding drift.

6. Analytics, Window Functions, and CTEs

  • Window functions

    SELECT name, price,
      AVG(price) OVER (PARTITION BY category_id) AS category_avg,
      RANK()     OVER (PARTITION BY category_id ORDER BY price DESC) AS price_rank
    FROM products;

    Computes partition aggregates and rankings without collapsing rows like GROUP BY.

    Pitfall: ROW_NUMBER(), RANK(), and DENSE_RANK() break ties differently: pick the exact tie policy you need.

  • LAG / LEAD

    SELECT ordered_at, total,
      LAG(total)  OVER (ORDER BY ordered_at) AS prev_total,
      LEAD(total) OVER (ORDER BY ordered_at) AS next_total
    FROM orders_summary;

    Reads values from preceding or following rows within the partition order.

    Pitfall: The first LAG and last LEAD evaluate to NULL unless you pass a fallback 3rd argument.

  • CTE (WITH)

    WITH customer_spend AS (
      SELECT customer_id, SUM(quantity * unit_price) AS total_spend
      FROM order_items oi JOIN orders o ON o.id = oi.order_id
      GROUP BY customer_id
    )
    SELECT * FROM customer_spend WHERE total_spend > 500;

    Breaks complex multi-step queries into readable named stages.

    Pitfall: CTEs are scoped to a single statement and do not persist as temporary tables.

  • WITH RECURSIVE

    WITH RECURSIVE tree AS (
      SELECT id, name, parent_id, 1 AS depth
      FROM categories WHERE parent_id IS NULL
      UNION ALL
      SELECT c.id, c.name, c.parent_id, t.depth + 1
      FROM categories c JOIN tree t ON c.parent_id = t.id
    )
    SELECT * FROM tree ORDER BY depth, id;

    Traverses trees and hierarchies via an anchor member plus a recursive term.

    Pitfall: A cycle in parent_id links causes infinite recursion unless guarded by a cycle or depth check.

7. Writing Data, DDL, and Transactions

  • INSERT

    INSERT INTO customers (first_name, last_name, email, city, country, signed_up_on)
    VALUES ('Marco', 'Bianchi', 'm.b@example.com', 'Verona', 'Italy', CURRENT_DATE);
    
    INSERT INTO categories (name, parent_id)
    VALUES ('Gaming', 1)
    RETURNING id, name;

    Inserts rows and optionally returns generated defaults/IDs via RETURNING.

    Pitfall: Always name target columns explicitly so schema column additions do not break INSERT statements.

  • UPDATE

    UPDATE products
    SET price = price * 1.10
    WHERE category_id = 5;

    Updates only rows matching the WHERE predicate.

    Pitfall: Never run UPDATE without WHERE unless updating every row in the table is intentional.

  • DELETE

    DELETE FROM reviews
    WHERE rating < 3;

    Removes targeted rows while leaving table schema and indexes intact.

    Pitfall: Omitting WHERE deletes every row; referencing foreign keys without ON DELETE CASCADE blocks deletion.

  • CREATE TABLE

    CREATE TABLE wishlists (
      id          SERIAL PRIMARY KEY,
      customer_id INTEGER NOT NULL REFERENCES customers(id),
      product_id  INTEGER NOT NULL REFERENCES products(id),
      added_on    DATE    NOT NULL DEFAULT CURRENT_DATE,
      UNIQUE (customer_id, product_id)
    );

    Defines table columns, keys, foreign-key references, defaults, and uniqueness constraints.

    Pitfall: Standard SQL UNIQUE constraints still allow multiple NULLs unless combined with NOT NULL.

  • ALTER / DROP

    ALTER TABLE customers ADD COLUMN newsletter BOOLEAN NOT NULL DEFAULT false;
    ALTER TABLE customers DROP COLUMN newsletter;
    DROP TABLE wishlists;

    Alters table schema or removes a table altogether.

    Pitfall: DROP TABLE immediately destroys both data and schema; verify target database and dependencies first.

  • Transactions

    BEGIN;
    UPDATE products SET stock = stock - 1 WHERE id = 1;
    UPDATE products SET stock = stock + 1 WHERE id = 2;
    COMMIT;     -- or ROLLBACK;

    Groups multiple statements into an atomic ACID unit.

    Pitfall: Leaving idle transactions open holds row locks and blocks concurrent writers.