Queries and Joins
7 pages · ~5 min✓ Reviewed
Start here. Next up: Aggregates and GROUP BY.
SELECT Query Mental Model
1. What a query is
SELECTpicks columns,FROMnames the table- A query describes the result you want
- The engine chooses how to fetch it
- Avoid
SELECT *in production code
sql
SELECT name, city FROM users;
only the columns you need
2. Logical order
- FROM / JOIN
- WHERE
- GROUP BY
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- LIMIT
- A SELECT alias works in ORDER BY (runs after SELECT)
Filtering, Sorting and Limiting
1. Filtering Rows
WHEREfilters rows before groupingANDbinds tighter thanOR: add parenthesesBETWEENincludes both ends
| Operator | Meaning |
|---|---|
= / <> | equal / not equal |
IN (1,2,3) |
NULL Handling
1. What NULL means
- NULL = unknown, not 0 or empty string
- Any comparison with NULL yields UNKNOWN
col = NULLnever matches any row- Use
IS NULL/IS NOT NULL
2. Filtering with NULL
WHEREkeeps only rows that are TRUE- UNKNOWN rows are dropped
NOT IN (1, NULL)returns no rows
INNER, LEFT, RIGHT and FULL Joins
1. What a join does
- A join combines rows from two tables on a condition
ONnames the matching columns; aliases keep them short
sql
SELECT o.id, u.name FROM orders o JOIN users u ON o.user_id = u.id;
2. Join types
| Join | Keeps | No match |
|---|---|---|
CROSS Joins, Self Joins and Join Mistakes
1. CROSS and self joins
- CROSS JOIN = every pairing, m × n rows
- No
ONclause; use it to generate combinations - Self join: same table twice, with aliases
sql
SELECT e.name, m.name AS manager FROM emp e LEFT JOIN emp m ON e.manager_id = m.id
2. Join mistakes
| Mistake |
|---|
SQL Querying Cheat Sheet
1. Query Order
- Written:
SELECT→FROM→JOIN→WHERE→ORDER BY→LIMIT - Runs: FROM → WHERE → SELECT → ORDER BY → LIMIT
- An alias from
SELECTworks inORDER BY, not inWHERE
- FROMrows
- WHEREfilter
- SELECTcolumns
- ORDER BYsort
- LIMITcut
Check yourself
Table t has ids 1, 2, 3. What does SELECT id FROM t WHERE id NOT IN (1, NULL) return?
- None
- Row 1 fails id <> 1; rows 2 and 3 give UNKNOWN against NULL, so all are dropped.
Asha has no orders, Ben has a paid one. Who does this return?
- Only Ben
- Asha's o.status is NULL, so WHERE is UNKNOWN and drops her
- Put the status test in ON to keep her
FROM users u LEFT JOIN orders o ON o.user_id = u.id WHERE o.status = 'paid'