Conditions and missing values

Lesson 4 of 18 · SQL foundations

WHERE keeps rows for which a condition is true. Comparisons include =, <>, <, <=, > and >=. In SQL, an unknown result is not true, so WHERE excludes it.

SELECT title FROM books
WHERE (shelf_id = 1 OR shelf_id = 2) AND pages BETWEEN 80 AND 120
ORDER BY id;

The result is Moss Atlas and River Notes. Both endpoints of BETWEEN are included. AND requires both conditions; OR requires at least one. Parentheses clarify the intended grouping; without them AND binds more tightly than OR. shelf_id IN (1, 2) is a compact alternative for this list.

SELECT title FROM books WHERE pages IS NULL ORDER BY id;

This returns Night Sky. Use IS NULL or IS NOT NULL, not = NULL: ordinary comparison with NULL yields unknown. Be careful with NOT IN when its list or subquery contains NULL; unknown can prevent expected matches.

For example, pages > 100 is unknown for Night Sky. So is NOT (pages > 100); neither condition includes that row. To include unknown page counts deliberately, add OR pages IS NULL. NOT reverses true and false, but leaves unknown unknown.

Chapter index · Course index