
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.
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:
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
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; -- paginateAdd 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:
flowchart LR
A["FROM / JOIN"] --> B["WHERE<br/>filter rows"]
B --> C["GROUP BY<br/>make groups"]
C --> D["HAVING<br/>filter groups"]
D --> E["SELECT<br/>window functions, aliases"]
E --> F["DISTINCT"]
F --> G["ORDER BY"]
G --> H["LIMIT / OFFSET"]2. Filtering with WHERE
Operator | Example | Meaning |
|---|---|---|
|
| Equal, not equal ( |
|
| Comparison |
|
| Inclusive on both ends |
|
| Matches any value in the list |
|
|
|
|
| Missing value (never use |
|
| Combine conditions; use parentheses |
3. Aggregates and Grouping
Function | Returns |
|
|---|---|---|
| Number of rows | Counted |
| Number of non- | Skipped |
| Number of unique non- | Skipped |
| 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 |
|---|---|
| Only rows that match in both tables |
| All left rows, plus matches from the right ( |
| All right rows, plus matches from the left |
| All rows from both tables |
| Every left row paired with every right row |
Joining Table A (ids 1, 2, 3) with Table B (ids 2, 3, 4) on id:
flowchart LR
A["Table A<br/>ids: 1, 2, 3"]
B["Table B<br/>ids: 2, 3, 4"]
A --> I["INNER JOIN<br/>2, 3"]
B --> I
A --> L["LEFT JOIN<br/>1, 2, 3"]
B --> L
A --> R["RIGHT JOIN<br/>2, 3, 4"]
B --> R
A --> F["FULL JOIN<br/>1, 2, 3, 4"]
B --> FTip: 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 |
|
Numeric |
|
NULL handling |
|
Dates |
|
Conversion |
|
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 |
|---|---|
| Rows from both queries, duplicates removed |
| Rows from both queries, duplicates kept (faster) |
| Rows that appear in both |
| Rows in the first but not the second ( |
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 |
|
|
|
|---|---|---|---|
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
WHEREonUPDATEandDELETE. Without it, every row is changed. Test the filter with aSELECTfirst.
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 BEGIN9. 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 itselfType | Use for |
|---|---|
| Whole numbers, IDs |
| Money and exact numbers (avoid |
| Text |
| Dates and date-times |
| True / false ( |
10. Dialect Differences
Task | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
Limit rows |
|
|
|
Current date |
|
|
|
Current timestamp |
|
|
|
Year of a date |
|
|
|
Truncate to month |
|
|
|
Concatenate text |
|
|
|
Text length |
|
|
|
Auto-increment ID |
|
|
|
Upsert |
|
|
|
Full outer join |
| Not supported |
|
11. Pre-Flight Checklist
Use
IS NULL, not= NULL.Filter groups with
HAVING, rows withWHERE.Every join except
CROSS JOINneeds anONcondition.Every
LIMITneeds anORDER BY.Every
UPDATEandDELETEneeds aWHERE, tested withSELECTfirst.Use
NOT EXISTSinstead ofNOT INwhenNULLs 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.
Comments(0)
Join the discussion by logging into your account.
No comments yet. Be the first to comment!