Skip to main content

SQL Cheat Sheet: One-Page Quick Reference

A bookmark-worthy SQL reference covering queries, joins, window functions, and more, with diagrams and MySQL and SQL Server differences.

Updated 8 min readMarkdown
SQL Cheat Sheet: One-Page Quick Reference

Bookmark this page. It covers the syntax you'll use most, with short examples and diagrams for the parts people forget. Examples use PostgreSQL syntax; a dialect table near the end lists where MySQL and SQL Server differ.

Mermaid Diagram

The examples use these two tables:

Mermaid Diagram


1. Query Anatomy

SELECT   c.city, COUNT(*) AS order_count              -- what to return
FROM     customers c                                  -- where it comes from
JOIN     orders o ON o.customer_id = c.customer_id    -- combine tables
WHERE    o.status = 'completed'                       -- filter rows
GROUP BY c.city                                       -- build groups
HAVING   COUNT(*) > 5                                 -- filter groups
ORDER BY order_count DESC                             -- sort
LIMIT    10 OFFSET 20;                                -- paginate

Add DISTINCT after SELECT to remove duplicate result rows. You write SELECT first, but SQL processes the query in the logical order below, which is why most databases reject aliases and aggregates in WHERE:

Mermaid Diagram


2. Filtering with WHERE

Operator Example Meaning
=, <> status = 'completed' Equal, not equal (!= also works in most databases)
<, <=, >, >= amount >= 100 Comparison
BETWEEN amount BETWEEN 10 AND 50 Inclusive on both ends
IN city IN ('Paris', 'Rome') Matches any value in the list
LIKE first_name LIKE 'A%' % = any characters, _ = one character
IS NULL phone IS NULL Missing value (never use = NULL)
AND, OR, NOT (a OR b) AND c Combine conditions; use parentheses

3. Aggregates and Grouping

Function Returns NULLs
COUNT(*) Number of rows Counted
COUNT(col) Number of non-NULL values Skipped
COUNT(DISTINCT col) Number of unique non-NULL values Skipped
SUM, AVG, MIN, MAX Total, mean, smallest, largest Skipped
SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total
FROM orders
WHERE status = 'completed'       -- filters rows before grouping
GROUP BY customer_id
HAVING SUM(amount) > 1000        -- filters groups after aggregating
ORDER BY total DESC;

Rule: every non-aggregated column in SELECT must be listed in GROUP BY.


4. Joins

SELECT c.first_name, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
Join Keeps
INNER JOIN Only rows that match in both tables
LEFT JOIN All left rows, plus matches from the right (NULL if none)
RIGHT JOIN All right rows, plus matches from the left
FULL JOIN All rows from both tables
CROSS JOIN Every left row paired with every right row

Joining Table A (ids 1, 2, 3) with Table B (ids 2, 3, 4) on id:

Mermaid Diagram

Tip: to filter the right table of a LEFT JOIN, put the condition in ON, not WHERE; a WHERE condition on right-side columns silently turns it into an inner join. The one exception is WHERE o.order_id IS NULL, which finds left rows with no match.


5. Common Functions

Type Functions
Text UPPER(s), LOWER(s), TRIM(s), LENGTH(s), SUBSTRING(s, start, len), REPLACE(s, from, to), CONCAT(a, b)
Numeric ROUND(x, n), CEIL(x) / CEILING(x), FLOOR(x), ABS(x), MOD(x, y) or x % y
NULL handling COALESCE(a, b, ...) first non-NULL; NULLIF(a, b) returns NULL if equal
Dates CURRENT_DATE, CURRENT_TIMESTAMP, EXTRACT(YEAR FROM d), DATE_TRUNC('month', d) (date functions vary a lot; see the dialect table)
Conversion CAST(x AS type) (PostgreSQL also accepts x::type)

CASE expression

SELECT order_id,
       CASE WHEN amount >= 500 THEN 'large'
            WHEN amount >= 100 THEN 'medium'
            ELSE 'small'
       END AS order_size
FROM orders;

6. Subqueries, CTEs, and Set Operations

-- CTE: a named, reusable subquery
WITH big_spenders AS (
    SELECT customer_id, SUM(amount) AS total
    FROM orders
    GROUP BY customer_id
    HAVING SUM(amount) > 1000
)
SELECT c.first_name, b.total
FROM big_spenders b
JOIN customers c ON c.customer_id = b.customer_id;

-- EXISTS: does a related row exist?
SELECT first_name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

-- Prefer NOT EXISTS over NOT IN when the subquery can return NULL
SELECT first_name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Operator Result
UNION Rows from both queries, duplicates removed
UNION ALL Rows from both queries, duplicates kept (faster)
INTERSECT Rows that appear in both
EXCEPT Rows in the first but not the second (MINUS in Oracle)

Both queries need the same number of columns with compatible types. (MySQL supports INTERSECT and EXCEPT from version 8.0.31.)


7. Window Functions

Window functions calculate across related rows without collapsing them into one row.

SELECT order_id, customer_id, amount,
       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn,
       LAG(amount)  OVER (PARTITION BY customer_id ORDER BY order_date)      AS prev_amount,
       SUM(amount)  OVER (PARTITION BY customer_id ORDER BY order_date
                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)  AS running_total
FROM orders;

PARTITION BY splits rows into groups, ORDER BY orders rows inside each group. Here's how the ranking functions treat ties, for scores 100, 100, 90:

Score ROW_NUMBER() RANK() DENSE_RANK()
100 1 1 1
100 2 1 1
90 3 3 2

Other useful ones: LEAD() (next row), NTILE(n) (split into n buckets), FIRST_VALUE().

You can't filter on a window function in WHERE. To keep only rn = 1, wrap the query in a CTE or subquery first.


8. Changing Data

INSERT INTO customers (first_name, city) VALUES ('Anna', 'London');   -- assumes customer_id auto-generates

UPDATE orders SET status = 'cancelled' WHERE order_id = 1042;

DELETE FROM orders WHERE order_id = 1042;

-- Upsert (PostgreSQL)
INSERT INTO customers (customer_id, first_name) VALUES (1, 'Anna')
ON CONFLICT (customer_id) DO UPDATE SET first_name = EXCLUDED.first_name;

Always include WHERE on UPDATE and DELETE. Without it, every row is changed. Test the filter with a SELECT first.

Transactions

BEGIN;       -- START TRANSACTION in MySQL, BEGIN TRANSACTION in SQL Server
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;      -- or ROLLBACK; to undo everything since BEGIN

9. Defining Structure

CREATE TABLE orders (
    order_id    INT PRIMARY KEY,
    customer_id INT NOT NULL,
    order_date  DATE NOT NULL DEFAULT CURRENT_DATE,
    amount      DECIMAL(10,2) CHECK (amount >= 0),
    status      VARCHAR(20),
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

ALTER TABLE orders ADD COLUMN notes TEXT;
ALTER TABLE orders DROP COLUMN notes;
CREATE INDEX idx_orders_customer ON orders (customer_id);
TRUNCATE TABLE orders;    -- destructive: deletes all rows, keeps the table
DROP TABLE orders;        -- destructive: deletes the table itself
Type Use for
INT, BIGINT Whole numbers, IDs
DECIMAL(p, s) Money and exact numbers (avoid FLOAT for money)
VARCHAR(n), TEXT Text
DATE, TIMESTAMP Dates and date-times
BOOLEAN True / false (BIT in SQL Server)

10. Dialect Differences

Task PostgreSQL MySQL SQL Server
Limit rows LIMIT 10 LIMIT 10 SELECT TOP 10 or OFFSET ... FETCH
Current date CURRENT_DATE CURRENT_DATE CAST(GETDATE() AS DATE)
Current timestamp NOW() NOW() GETDATE()
Year of a date EXTRACT(YEAR FROM d) EXTRACT(YEAR FROM d) or YEAR(d) YEAR(d) or DATEPART(year, d)
Truncate to month DATE_TRUNC('month', d) DATE_FORMAT(d, '%Y-%m-01') (text result) DATETRUNC(month, d) (2022+)
Concatenate text CONCAT() or the double-pipe operator CONCAT() CONCAT() or +
Text length LENGTH() CHAR_LENGTH() LEN()
Auto-increment ID GENERATED ... AS IDENTITY AUTO_INCREMENT IDENTITY(1,1)
Upsert ON CONFLICT ON DUPLICATE KEY UPDATE MERGE
Full outer join FULL JOIN Not supported FULL JOIN

11. Pre-Flight Checklist

  • Use IS NULL, not = NULL.

  • Filter groups with HAVING, rows with WHERE.

  • Every join except CROSS JOIN needs an ON condition.

  • Every LIMIT needs an ORDER BY.

  • Every UPDATE and DELETE needs a WHERE, tested with SELECT first.

  • Use NOT EXISTS instead of NOT IN when NULLs are possible.

Keep this page open while you work, and most day-to-day queries become a matter of looking up the pattern and filling in your table and column names.


Published via ZyVOP — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.

About the author

  • One platform to write, cross-post to Dev.to, Medium, WordPress, Hashnode, and Bluesky, and protect your SEO with canonical links. Zero paywalls and full content ownership.

No comments yet. Be the first to comment.