Order of Execution, NULL Filters, Aggregation, GROUP BY & HAVING
How a query really runs, how to filter unknown values, and how to summarise data with WHERE versus HAVING.
1. The Crux in 60 Seconds
Know the run order
FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then TOP. Aliases from SELECT therefore work in ORDER BY but not in WHERE or HAVING.
NULL needs IS NULL
city = NULL returns nothing, because unknown cannot be compared, even with itself. Use IS NULL / IS NOT NULL.
Aggregate with GROUP BY
COUNT, SUM, MAX, MIN, AVG summarise rows; GROUP BY gives one row per group, like an Excel pivot table. Aggregates ignore NULLs.
WHERE vs HAVING
WHERE filters rows before grouping; HAVING filters grouped (aggregated) results. Row-level conditions belong in WHERE.
2. Foundational Concepts & Comparisons
WHERE (row-level filter)
- Checks each row independently, ignoring neighbouring rows
- Runs right after FROM, so it can only use real table columns
- Cannot use aggregates or SELECT aliases
- Cheaper: shrinks the data before costly aggregation
HAVING (aggregate-level filter)
- Works on groups after GROUP BY has formed them
- Can use aggregates such as
SUM(sales), and grouping columns - Runs before SELECT, so SELECT aliases fail here too
- A group comes out complete or not at all, never partially
Assignment review: "customer name neither starts with A nor ends with N"
The instructor admitted the wording was confusing. The intent: exclude names that start with A and end with N (a name such as "Ankit" is therefore kept, because it does not end with N).
WHERE customer_name NOT LIKE 'a%n'
One pattern, one negation: starts with a, anything in the middle, ends with n. Fastest option.
WHERE NOT (customer_name LIKE 'a%'
AND customer_name LIKE '%n')Negate a bracketed group of conditions. Same result, but three operations.
The positive match returned 179 rows under either form, and the negated version returned 9,815. Two separate NOT LIKE conditions are a different test: read the whole condition as one unit, not word by word. NOT IN does not suit this: IN / NOT IN compare exact values, so patterns need LIKE.
Pattern matching limits
LIKEonly filters; it never modifies data. Removing hyphens from phone numbers needs aREPLACEfunction (covered with functions)- ESCAPE: the instructor believes several characters can be listed (for example % and _) and promised to test and confirm
Warm-up note
- Keywords (WHERE, AND, NOT LIKE) show in colour in the editor
- Where a student asked about
LIKEon a text column such as phone numbers, the same rule held: use it to search, not to change