# 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](https://mermaid.ink/img/pako:eNpd0U2P2yAQBuC_Mp0zjrRSTzlU8gfZuErsrT92W4UciI0TVAwRxnV3o_z3CqdbdXNkmPcBhgs2phW4xE6ZqTlx66BKmAYA-HZhmMLEtQNnFosFw-vfDQiCLxDuGBaCt9Byxxnub8WHHcOSbmhcEXhZ04ISyIuEFhD9ILBJt2nFcP8_E_nA2PfcyjfxwYq8Fed1VhEo6y2BxyKvn2ZoHT6n2eOdFPt20x-kFuD4QYnhXYq99DVPMwJ1lubZXTC5Bc_cCrBm-hdLfOxF6tZM0I26cdLogUBc0eFOoF44cX38-ALqgTQraVERqJ-SsKIEErqhFb0DVjuG0ShVC4OzY-NGK96R1TyGgs7hcFPRgkCaJfQ7wz0S7IXtuWxxeUF3Er3_ylZ0fFQOya3yzK2cx-F7OqPdivdSveISA34-KxEMr4MTPYFISf1zy5tyXq-MdgQYluJoBNQpQwKFORhnCKyF-iWcbDiB0EquCAxcD8EgrOyQzIeU8s3f5eHz-TderwQPx9goY3GJn6aTdAKvfwDf4L03?type=png)

The examples use these two tables:

![Mermaid Diagram](https://mermaid.ink/img/pako:eNplUMtOw0AM_BXj8-aAxCk3aKlAqCpqKKdKlZu4rcU-ol0HKGn-HaWpBGp8sWfG1ozcYhkqxhw5ToX2kdzaAwBMVsXbYv64LOB0yrLQwmI57VEOtaWS0_VWOxB9iVcom6TBcdxIBa8vf1rSKH4PO4lJN54cj6T6EPyYLUWPA9kN7RLnyjbEaux5nWf2T6tI-XLVj_8ELsWRBXKh8TrKk5S0uTyhQ4OOoyOpMG9RD-z6h1a8o8YqmoF5pyi0tZz6nV3wOiMn9og5ZlTXlrN0TMrOwIMV_zGnsjjjWfBqYI0F7wPD6nmNBpZhGzQYeGL7ySolGbiPQtZAIp-yxFF2aM4mhfz0WW7v6m_sOoPb_STYEDHHm6-DKGP3C58woW8?type=png)

* * *

## 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 Diagram](https://mermaid.ink/img/pako:eNpdkFFrwjAQx7_K7Z5TZLAnGYKtre1QO1rdkMaHtKYaTBtJ4jonfvfRCDr2ePf7_e-Ou2ClthyHWEvVVXumLcwy2gIAjAuKUZbOYQBvabKguAHPG4FfUPyMwyx8LfVgVAtpuQatOkNxcwv6zgsKitMsXb2Dv3Zqww4cdlqdjg81cOqkoBiPP5LF9O_Mf-rEqWFBMQ9nYbB0aifareqgPrWVFao1BJgUzPBHLHSxqKA4SfJlsgiWdxQ5NC0optkkzMBf39HUobigOEvmyRIGkEZRHvZZJNhw3TCxxeEF7Z43_fu2vGYnaZHcOh9MC1ZKbnqnVq2NWCPkGYfoseNRcs-cjeUNAV-K9jBnVe7qSLWWAMWc7xSHVUKRQKZKZRWBmMsvbkXFCIy1YJKAYa3xDNeiRuKW5OKnv-X55fiN1yvBchcoqTQO8anbC8vx-gugqZfO?type=png)

* * *

## 2\. Filtering with `WHERE`

| Operator | Example | Meaning |
| --- | --- | --- |
| =, &lt;&gt; | status = 'completed' | Equal, not equal (!= also works in most databases) |
| &lt;, &lt;=, &gt;, &gt;= | amount &gt;= 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 |

```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 Diagram](https://mermaid.ink/img/pako:eNplkMFugkAQhl9lOuchja0n0phgI5WG2gS1F7aHBRbZdGHJ7rbWGt-9ARLFeJzJ980_-Y-Y60Kgj6XS-7zixkGcsAYAIEgZbnimBARPmbmfycL6MCF4IHhk-DlA8zM0v0AdQTA9QwF43gyilGG0Wi0SeH2PVj19fWqgxkqcMowX4eZi3OQP3FhKUoZJ9LLcXOeMHxqsZGyFKcNwG8c3UbdeiIS1MDWXBfpHdJWouwYLUfJv5ZCGzQc3sivGdkypGxfyWqoD-ujxtlXCswfrRE0wV7L5euP5up9D3TgChmux0wK2EUOCRGfaaYKlUD_CyZwTBEZyRWB5Yz0rjCyR-pC1_Ot-mUzbXzydCLPds1baoI93-0o6gad_RTOMhw?type=png)

**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.

---

*Published via [ZyVOP](https://zyvop.com/sql-cheat-sheet-one-page-quick-reference-0rw5p?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
