Skip to main content
Albero Academy

Filtering in Depth

Master the WHERE clause — comparison and logical operators, LIKE patterns, IN, BETWEEN, and the crucial rules for handling NULL.

Chapter 6SQL15 min readBeginner friendly
  • #SQL
  • #WHERE
  • #Filtering

Filtering rows is the most common thing you do in SQL, and the WHERE clause is deceptively deep — especially where NULL is concerned, which trips up almost everyone. This chapter covers the full toolkit for selecting exactly the rows you want.

Comparison & logical operators

combining conditions
SELECT * FROM students
WHERE package > 6
AND enrolled >= '2026-01-01'
AND (programme = 'Data' OR programme = 'Full Stack');
-- Operators: = <> < <= > >= and AND / OR / NOT
-- Parenthesise mixed AND/OR — precedence gives AND before OR.

LIKE patterns

LIKE matches text patterns with two wildcards: % (any sequence) and _ (one character):

pattern matching
WHERE name LIKE 'A%' -- starts with A
WHERE email LIKE '%@gmail.com' -- ends with
WHERE name LIKE '%aan%' -- contains
WHERE code LIKE 'D_2%' -- D, any char, 2, then anything
-- ILIKE (Postgres) is case-insensitive; elsewhere use LOWER(name) LIKE …

IN & BETWEEN

lists & ranges
WHERE programme IN ('Data', 'Full Stack', 'DevOps') -- any of a list
WHERE programme NOT IN ('Archived')
WHERE package BETWEEN 5 AND 8 -- inclusive range (5 ≤ x ≤ 8)
WHERE enrolled BETWEEN '2026-01-01' AND '2026-03-31';

Handling NULL

NULL means "unknown", and it does not behave like a value. Any comparison to NULL (even = NULL) yields "unknown", never true — so you must use IS NULL / IS NOT NULL:

NULL is special
WHERE email IS NULL -- ✓ finds missing emails
WHERE email = NULL -- ✗ NEVER matches anything
-- NULL also drops out of other conditions:
WHERE package <> 8 -- excludes rows where package IS NULL too!
-- To keep them:
WHERE package <> 8 OR package IS NULL;

Practice

On a students table, write filters for: names starting with "A", packages between 6 and 9, a programme in a list of three, students with no recorded email, and everyone whose package isn't 8 including those with an unknown package.

Key takeaways

  1. 01Combine conditions with AND/OR/NOT — parenthesise when mixing (AND binds tighter than OR).
  2. 02LIKE matches patterns: % (any sequence), _ (one char); use LOWER()/ILIKE for case-insensitivity.
  3. 03IN tests membership in a list; BETWEEN tests an inclusive range.
  4. 04NULL means unknown — comparisons to it are never true; use IS NULL / IS NOT NULL.
  5. 05NULLs silently drop out of <>/>/< filters — handle them explicitly.