2.4 — Multi-Condition Filtering
What You'll Learn
- How to use
AND
,OR
, and parentheses to combine filters - How this compares to advanced Excel filters
Combining Conditions
Excel:
Use "Custom Filter" to show rows where Product is "Apples" and Amount is greater than 100.
SQL:
SELECT * FROM sales
WHERE Product = 'Apples' AND Amount > 100;
AND
means both conditions must be true.
Using OR
Show sales for "Apples" or "Oranges":
SELECT * FROM sales
WHERE Product = 'Apples' OR Product = 'Oranges';
OR
means either condition can be true.
Grouping with Parentheses
Show sales for "Apples" with Amount > 100, or any sales for "Oranges":
SELECT * FROM sales
WHERE (Product = 'Apples' AND Amount > 100)
OR Product = 'Oranges';
- Parentheses control the order of logic, just like in Excel formulas.
Special Note on NULL Values
NULL
means missing or unknown data.Comparisons like
= NULL
or<> NULL
do not work.Use
IS NULL
orIS NOT NULL
:sqlWHERE Amount IS NULL
Common Mistakes to Avoid
Using
=
or<>
with NULL:sqlWHERE Amount = NULL -- Incorrect! WHERE Amount <> NULL -- Incorrect!
Always use
IS NULL
orIS NOT NULL
for NULL checks.Forgetting Parentheses in Complex Conditions:
sqlWHERE Product = 'Apples' AND Amount > 100 OR Product = 'Oranges'
This may not filter as you expect. Use parentheses to clarify:
sqlWHERE (Product = 'Apples' AND Amount > 100) OR Product = 'Oranges'
Forgetting quotes around text values:
sqlWHERE Product = Apples -- Incorrect! WHERE Product = 'Apples' -- Correct
Case sensitivity:
Some databases treat'apples'
and'Apples'
as different. UseLOWER()
for case-insensitive comparisons if needed:sqlWHERE LOWER(Product) = 'apples'
Key Points
- Combine conditions with
AND
,OR
, and parentheses for advanced filtering. - Always use
IS NULL
to check for missing data.
Next Steps
In the next module, you'll learn how to transform and sort your data—just like using formulas and sorting in Excel.