🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

SQL Cheatsheet: Clauses, Commands, Patterns

ReferenceReferenceđŸŸĸ Free Lesson
Reference

SQL Cheatsheet: Clauses, Commands, Patterns

Keep this page open while you work. Every block here is the shortest correct form of a task you will do hundreds of times.

  • Clause order — the sequence the parser enforces, and the mental order for writing
  • Quick tables — filtering, joining, grouping, shaping, and window syntax side by side
  • Command families — DDL, DML, DCL, and TCL with the exact statements you need
  • Copy-ready patterns — upserts, top-N-per-group, running totals, and safe deletes Bookmark it; the goal is recall speed, not memorization for its own sake.

Prerequisites

  • !Basic knowledge of SELECT, FROM, and WHERE
  • !Access to any SQL engine to try the snippets

What You'll Learn

  • 1Recall the legal clause order of a SELECT statement instantly
  • 2Look up filtering, grouping, and window syntax without leaving the page
  • 3Pick the right command family (DDL, DML, DCL, TCL) for a task
  • 4Adapt copy-ready patterns such as upserts and top-N-per-group to your engine

Clause Order: Written versus Executed

SQL is read top to bottom by humans and executed in a different order by the engine. Knowing both explains why a column alias defined in SELECT cannot be used in WHERE, and why filtering happens before sorting.

You writeThe engine executesWhat it does
FROM / JOIN1Sources rows; builds the working set
WHERE2Filters rows before grouping
GROUP BY3Collapses rows into groups
HAVING4Filters groups after aggregation
SELECT5Evaluates expressions and aliases
DISTINCT6Removes duplicate result rows
ORDER BY7Sorts the result
LIMIT / OFFSET8Truncates the sorted result

To filter on an aggregate, use HAVING or a subquery. To filter on an alias you just computed, wrap the query in a CTE and filter in the outer query — the clearest portable fix.

Filtering and Pattern Matching

TaskSyntaxNotes
RangeWHERE amount BETWEEN 10 AND 50Inclusive on both ends
MembershipWHERE status IN ('new', 'open')Watch NULLs with NOT IN
Null checkWHERE deleted_at IS NULLNever = NULL
PatternWHERE name LIKE 'Acme%'% any sequence, _ one character
Case-insensitiveWHERE name ILIKE '%acme%'PostgreSQL; use LOWER() elsewhere
RegexWHERE name ~* '^acme'PostgreSQL ~ / ~*; REGEXP in MySQL
Any of two conditionsWHERE a = 1 OR b = 2Prefer OR of indexed terms over IN on functions
All of two conditionsWHERE a = 1 AND b = 2Evaluate selective conditions the planner can reorder
Not equalWHERE status <> 'done'NULL rows drop out; add OR status IS NULL if needed
Exists related rowWHERE EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)Usually better than IN for correlated checks

Join Syntax at a Glance

JoinSyntaxKeeps
InnerFROM a INNER JOIN b ON a.id = b.a_idOnly matching pairs
LeftFROM a LEFT JOIN b ON a.id = b.a_idAll of a, matches from b
FullFROM a FULL OUTER JOIN b ON a.id = b.a_idAll rows from both sides
SelfFROM employees e JOIN employees m ON e.manager_id = m.idHierarchical relationships
CrossFROM a CROSS JOIN bEvery combination — always add a filter or a purpose
AntiFROM a LEFT JOIN b ON ... WHERE b.id IS NULLa rows with no match
SemiWHERE EXISTS (SELECT 1 FROM b WHERE ...)a rows with any match, no duplication

A quick sanity check before aggregating a join: compare COUNT(*) to COUNT(DISTINCT a.id). If they differ, the join fans out and your sums are inflated.

Grouping, Windowing, and Shaping

-- One query, many cheatsheet staples: filter, group, rank, and shape
WITH monthly_sales AS (
    SELECT
        c.region,
        c.customer_id,
        DATE_TRUNC('month', o.order_date) AS month,
        SUM(o.total) AS revenue
    FROM customers c
    INNER JOIN orders o ON o.customer_id = c.customer_id
    WHERE o.order_date >= DATE '2024-01-01'
      AND o.status <> 'cancelled'
    GROUP BY c.region, c.customer_id, DATE_TRUNC('month', o.order_date)
),
ranked AS (
    SELECT
        region,
        month,
        customer_id,
        revenue,
        ROW_NUMBER() OVER (PARTITION BY region, month ORDER BY revenue DESC) AS rn,
        SUM(revenue) OVER (PARTITION BY region ORDER BY month
            ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rev_3mo_trailing
    FROM monthly_sales
)
SELECT
    region,
    month,
    customer_id,
    revenue,
    rev_3mo_trailing
FROM ranked
WHERE rn <= 5          -- top 5 customers per region per month
ORDER BY region, month, revenue DESC;
TaskPattern
Aggregate by groupGROUP BY cols with HAVING SUM(x) > n
Running totalSUM(x) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING)
Moving averageAVG(x) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
Rank within groupROW_NUMBER() / RANK() / DENSE_RANK() OVER (PARTITION BY g ORDER BY v DESC)
Top N per groupFilter ROW_NUMBER() = 1 in a subquery or CTE
Period comparisonLAG(x) OVER (ORDER BY month) then x - LAG(x)
Percent of total100.0 * x / SUM(x) OVER ()
Gap-and-islandCompare ROW_NUMBER() over two orderings to form island keys

DDL, DML, DCL, and TCL Command Reference

FamilyStatementsTypical use
DDLCREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX, CREATE VIEWShape the schema
DMLINSERT, UPDATE, DELETE, MERGEChange rows
DCLGRANT, REVOKEControl access
TCLBEGIN, COMMIT, ROLLBACK, SAVEPOINTGroup changes atomically
-- Copy-ready DDL and DML patterns
-- Create a table with sensible keys and constraints
CREATE TABLE order_status_history (
    history_id   BIGSERIAL PRIMARY KEY,
    order_id     BIGINT NOT NULL REFERENCES orders (order_id),
    old_status   TEXT,
    new_status   TEXT NOT NULL,
    changed_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_osh_order_time ON order_status_history (order_id, changed_at DESC);

-- Insert or update (upsert) on a unique key — PostgreSQL form
INSERT INTO order_status_history (order_id, old_status, new_status)
VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING;

-- MySQL equivalent of an upsert
-- INSERT INTO order_status_history (order_id, old_status, new_status)
-- VALUES (?, ?, ?)
-- ON DUPLICATE KEY UPDATE new_status = VALUES(new_status);

-- Transactional multi-step change with explicit boundaries
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

String, Date, and Null Utilities

TaskPostgreSQLMySQL
Current timestampnow()NOW()
Date truncationDATE_TRUNC('month', d)DATE_FORMAT(d, '%Y-%m-01')
Date difference in daysd2 - d1 (interval)DATEDIFF(d2, d1)
Concatenatea || ' ' || bCONCAT(a, ' ', b)
Split stringSTRING_TO_ARRAY(s, ',')— (8.0+: JSON_TABLE)
Replace nullCOALESCE(x, 0)IFNULL(x, 0)
ConditionalCASE WHEN x > 0 THEN 'pos' ELSE 'neg' ENDSame
CastCAST(x AS NUMERIC(10,2))CAST(x AS DECIMAL(10,2))

Safe Delete and Update Recipes

Never modify rows without a verifiable scope. The reliable recipe: select the target rows by primary key inside a transaction, inspect the count, then apply the change.

BEGIN;

-- 1. Identify the rows you intend to touch
SELECT o.order_id, o.status, o.total
FROM orders o
WHERE o.status = 'cancelled'
  AND o.order_date < DATE '2023-01-01';

-- 2. Delete via the same predicate, optionally scoped by keys from step 1
DELETE FROM orders o
WHERE o.status = 'cancelled'
  AND o.order_date < DATE '2023-01-01';

-- 3. Confirm affected-row count matches expectation, then:
COMMIT;
-- If anything looks off: ROLLBACK;

For incremental loads, prefer MERGE (where supported) or INSERT ... ON CONFLICT over delete-then-insert; they avoid windows where the table is incomplete and play better with replicas.

Session Settings Worth Memorizing

Session-level configuration changes behavior for your connection only, which makes them ideal for one-off investigations without risking other users. Learn the handful you will actually reach for.

SettingEnginesWhat it is for
SET LOCAL work_mem = '64MB'PostgreSQLRaise sort/hash memory for one transaction
SET search_path = core, publicPostgreSQLControl unqualified name resolution
SET statement_timeout = '5s'PostgreSQLKill runaway queries during testing
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTEDBothChoose concurrency semantics explicitly
EXPLAIN ANALYZE inside a transaction with rollbackBothMeasure write statements safely

Treat these as diagnostic tools, not permanent fixes: a session setting that saves a query in your laptop client tells you what configuration the server actually needs, which belongs in the server's config files and change review process. Pair every investigation setting with a note in your findings so the durable fix is not forgotten once the query finally returns.

Common Mistakes

Using WHERE on an aggregate instead of HAVING

Fix: Filter aggregates with HAVING, or compute them in a CTE and filter in the outer query

Assuming MySQL supports ILIKE, STRING_TO_ARRAY, or :: casts

Fix: Check the dialect table above and keep a per-engine variant of your snippets

Running unscoped UPDATE or DELETE statements

Fix: SELECT first inside a transaction, match on primary keys, verify counts, then commit

Forgetting that NOT IN drops everything when the list contains NULL

Fix: Use NOT EXISTS or NOT IN over a subquery that filters NULLs out

Best Practices

  • Keep this page or a printed copy within reach while onboarding to a new stack
  • Store engine-specific variants of upsert and date snippets in your team wiki
  • Validate any copy-pasted snippet against a small test table before production use
  • Prefer CTEs over inline aliases you cannot reference in WHERE

Key Takeaways

  • Write FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY — the engine executes in roughly that order
  • Joins plus aggregation are the most common source of inflated metrics; verify cardinality
  • Window functions replace many self-joins for ranking, running totals, and period comparisons
  • DDL, DML, DCL, and TCL are four command families with distinct blast radii
  • Scope every write statement and wrap it in a transaction you can roll back
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement