CASE Inside Aggregates, String & NULL Functions, Set Operations
Day 6 assignment review (pivoting with CASE), SQL Server string functions, COALESCE, CAST and ROUND, then UNION, INTERSECT and EXCEPT.
The Crux in 60 Seconds
CASE inside SUM pivots rows to columns
SUM(CASE WHEN ... THEN sales END) gives separate columns (returned sales, 2019 sales, 2020 sales) per group. Most complex interview questions are this pattern.
Combine position functions
SUBSTRING takes start position and length; CHARINDEX finds a position; use them together with LEFT to cut a first name or a year out of text.
NULL handling for reports
ISNULL takes two arguments; COALESCE takes many and returns the first non-null value, left to right.
Set operations combine rows
UNION ALL keeps everything; UNION, INTERSECT and EXCEPT remove duplicates. Column count must match and types must be compatible. A join, by contrast, combines columns.
Foundational Concepts & Comparisons
JOIN
- Matches rows on a key and brings columns from both tables together.
Set operation
- Stacks rows of two queries vertically: 100 rows plus 200 rows gives 300 with UNION ALL.
UNION ALL vs UNION
- UNION ALL: every row, rows of table 1 plus rows of table 2.
- UNION: combines, sorts and removes duplicates, even duplicates inside one table.
INTERSECT vs EXCEPT
- INTERSECT: rows common to both.
- EXCEPT (MINUS in some databases): rows of the first query not in the second.
REPLACE vs TRANSLATE
- REPLACE swaps a whole string for another.
- TRANSLATE maps characters one to one (A to T, G to P).
ISNULL vs COALESCE
- ISNULL(column, default): two arguments only.
- COALESCE(a, b, c, ...): first non-null value; can end with a default.
INTERSECT vs INNER JOIN
- INTERSECT is a set operation without duplicates, handy when comparing many columns.
- Use a join when you need columns from both tables.
WHERE vs HAVING for spaces
- Checking each name for stray spaces is row by row, so WHERE. HAVING is only for filtering an aggregation.