--- title: "SQL Cheat Sheet: One-Page Quick Reference" author: "Alysaa Lissy" published: "2026-11-21T05:53:53.624Z" updated: "2026-11-21T05:54:56.495Z" url: "https://zyvop.com/sql-cheat-sheet-one-page-quick-reference-0rw5p" canonical: "https://zyvop.com/sql-cheat-sheet-one-page-quick-reference-0rw5p" tags: ["Window Functions","Quick Reference","SQL","databases","SQL Cheat Sheet"] --- # 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. ![Cover image]() 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 flowchart TD Q{"I want to..."} Q --> A["Read data"] --> A1["SELECT, WHERE, ORDER BY, LIMIT"] Q --> B["Summarize data"] --> B1["COUNT, SUM, GROUP BY, HAVING"] Q --> C["Combine tables"] --> C1["JOIN, UNION"] Q --> D["Compare rows"] --> D1["Window functions, CTEs"] Q --> E["Change data"] --> E1["INSERT, UPDATE, DELETE"] Q --> F["Build structure"] --> F1["CREATE, ALTER, INDEX"] ``` The examples use these two tables: ```mermaid erDiagram CUSTOMERS ||--o{ ORDERS : places CUSTOMERS { int customer_id PK string first_name string phone string city } ORDERS { int order_id PK int customer_id FK date order_date decimal amount string status } ``` * * * ## 1\. Query Anatomy ```sql 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 flowchart LR A["FROM / JOIN"] --> B["WHERE
filter rows"] B --> C["GROUP BY
make groups"] C --> D["HAVING
filter groups"] D --> E["SELECT
window functions, aliases"] E --> F["DISTINCT"] F --> G["ORDER BY"] G --> H["LIMIT / OFFSET"] ``` * * * ## 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 | `NULL`s | | --- | --- | --- | | `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 | ```sql 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 ```sql 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 flowchart LR A["Table A
ids: 1, 2, 3"] B["Table B
ids: 2, 3, 4"] A --> I["INNER JOIN
2, 3"] B --> I A --> L["LEFT JOIN
1, 2, 3"] B --> L A --> R["RIGHT JOIN
2, 3, 4"] B --> R A --> F["FULL JOIN
1, 2, 3, 4"] B --> F ``` **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 ```sql 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 ```sql -- 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. ```sql 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 ```sql 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 ```sql 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 ```sql 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 `NULL`s 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.