SQL Querying
SELECT Expressions and Filtering
SELECT derives the columns of a result, while WHERE chooses source rows whose search condition is true. Correct queries make expression meaning, null behavior, precedence, and duplicate intent explicit.- Projection is expression evaluation, not merely column selection.
WHEREretains only rows for which its condition evaluates toTRUE; bothFALSEandUNKNOWNare rejected.- Null needs dedicated predicates.
- Parenthesize mixed
ANDandORconditions to expose the intended grouping rather than relying on remembered precedence. DISTINCTapplies to the complete projected row and can hide an accidental many-to-many multiplication rather than fix it.- Filtering expressions influence access paths.
Derive a useful result after choosing rows
SELECT p.product_id,
p.name,
p.current_price,
CASE
WHEN p.current_price < 25 THEN 'budget'
WHEN p.current_price < 100 THEN 'standard'
ELSE 'premium'
END AS price_band
FROM products AS p
WHERE p.current_price >= 10
AND p.current_price < 500;The filter first keeps products priced from 10 up to, but not including, 500. For each survivor, the CASE expression derives exactly one price band. A price of 20 becomes budget; a null current_price is removed because both comparisons are unknown.
| Construct | Role | Commerce example |
|---|---|---|
| Alias | Name an output expression | quantity * unit_price AS line_total |
CASE | Conditional result | Map price ranges to display bands |
COALESCE | First non-null value | Show a fallback category label |
IS NULL | Test missing marker | Find products not discontinued |
DISTINCT | Remove duplicate result rows | Unique customer IDs, when uniqueness is truly intended |