SQL WHERE: filter rows and handle missing values
Build a condition, predict the included records and check boundary cases.
Start the worked examples ↓Keep completed or returned orders over $40
WITH orders(order_id, customer_id, amount_usd, status) AS (
VALUES (101, 1, 50.0, 'completed'),
(102, 1, 30.0, 'returned'),
(103, 2, 80.0, 'completed'),
(104, 3, NULL, 'pending')
)
SELECT order_id, status, amount_usd
FROM orders
WHERE status IN ('completed', 'returned') AND amount_usd > 40
ORDER BY order_id;Orders 101 and 103 remain. The IN list tests allowed statuses; AND also requires the amount condition.
Make mixed conditions explicit
AND binds more tightly than OR. Parentheses make the intended rule clear, for example: (status = ‘completed’ OR status = ‘returned’) AND amount_usd > 40. Change one condition at a time and predict the affected rows.
Test missing amounts separately
WITH orders(order_id, customer_id, amount_usd, status) AS (
VALUES (101, 1, 50.0, 'completed'),
(102, 1, 30.0, 'returned'),
(103, 2, 80.0, 'completed'),
(104, 3, NULL, 'pending')
)
SELECT order_id FROM orders WHERE amount_usd IS NULL;Expect order 104. NULL is not zero or an empty string. amount_usd = NULL evaluates to unknown and does not pass WHERE. A comparison such as amount_usd > 40 also excludes an unknown amount.
Does BETWEEN include both endpoints?
Yes. BETWEEN includes the start and the end. For adjacent timestamp reports, use an inclusive start and an exclusive next-period boundary so an order exactly at midnight belongs to one period. Ending at 23:59:59 can omit later fractional-second records. See the tested midnight-order example for exact row IDs and reconciled USD totals.
The PostgreSQL comparison reference defines BETWEEN and its inclusive boundaries. Choose the reporting timezone before defining timestamp boundaries; a calendar day and 24 elapsed hours are not always equivalent.
How is LIKE different from a range filter?
LIKE matches text patterns: % represents a sequence of characters and _ represents one character. Case behavior depends on dialect and collation. PostgreSQL offers ILIKE for case-insensitive matching. A text-pattern match does not replace a typed date or timestamp range.
How can I test my filter?
Include a row just below the threshold, a row exactly on it, a row just above it and a NULL. Then explain the effect of > versus >=. The examples here are code to run in a database, not a simulated Run button.
Continue learning
Reference: PostgreSQL tutorial. Check behaviour for your installed version.
These are educational exercises with fictional data, not a verified employer question bank. Amounts in examples are USD unless otherwise stated.
Practise your explanation
Use the self-practice guide to review your approach. Mock-interview booking and payment are currently inactive. All planned preparation sessions and feedback are in English.
View preparation options