Lesson 219 of 296
NULL, CASE and dates
What you will learn
- What NULL means and three-valued logic
- IS NULL, COALESCE, NULLIF and IS DISTINCT FROM
- NULLs in aggregates, sorting and unique constraints
- CASE expressions
- Working with dates, times and time zones
On this page
NULL means unknown
NULL is not zero, not an empty string, not false. It means unknown or missing. Any comparison or arithmetic with NULL gives NULL:
SELECT NULL = NULL AS equals, NULL IS NULL AS is_null, 1 + NULL AS plus,
'a' || NULL AS concat, NULLIF(0, 0) AS nullif_result;| equals | is_null | plus | concat | nullif_result |
|---|---|---|---|---|
| NULL | true | NULL | NULL | NULL |
NULL = NULL is not true: two unknown values are not known to be equal. So:
- Test with
IS NULL/IS NOT NULL, never= NULL. - SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. WHERE keeps only TRUE rows, which is why
city <> 'London'dropped Dara (Lesson 213) andNOT INwith a NULL returns nothing (Lesson 217).
Handling NULLs
SELECT name, COALESCE(city, 'Unknown') AS city FROM customers ORDER BY id;| name | city |
|---|---|
| Aisha Khan | London |
| Ben Smith | Leeds |
| Chen Li | London |
| Dara Patel | Unknown |
| Eve Jones | Manchester |
| Tool | Meaning |
|---|---|
COALESCE(a, b, c) | The first non-NULL value |
NULLIF(a, b) | NULL if a equals b, otherwise a. Classic use: avoid division by zero: total / NULLIF(count, 0) |
a IS DISTINCT FROM b | A NULL-safe "not equal": treats NULL as a comparable value |
SELECT name FROM customers WHERE city IS DISTINCT FROM 'London' ORDER BY id;| name |
|---|
| Ben Smith |
| Dara Patel |
| Eve Jones |
NULLs elsewhere
- Aggregates ignore NULLs (
AVGof 10, NULL, 20 is 15), exceptCOUNT(*). - Sorting: NULLs come last in ascending order in PostgreSQL (first in MySQL and SQL Server).
- Unique constraints: by default several rows may have NULL in a unique column (NULLs are not equal). PostgreSQL 15+ supports
UNIQUE NULLS NOT DISTINCTto allow only one. - Design: use
NOT NULLwherever a value must exist. Every nullable column is a question your code must answer.
CASE
CASE is SQL's if/else, usable anywhere an expression is allowed:
SELECT name, price_pence,
CASE
WHEN price_pence < 1000 THEN 'budget'
WHEN price_pence < 3000 THEN 'standard'
ELSE 'premium'
END AS band
FROM products
ORDER BY price_pence;| name | price_pence | band |
|---|---|---|
| Notebook | 450 | budget |
| Mug | 899 | budget |
| Pen Set | 1250 | standard |
| Desk Lamp | 2999 | standard |
| Kettle | 3499 | premium |
Conditions are checked in order; the first true one wins. Without ELSE, unmatched rows get NULL. CASE inside aggregates gives conditional counts and sums (Lesson 216).
Dates and times
| Type | Holds | Use |
|---|---|---|
date | A calendar day | Birthdays, order dates |
timestamptz | An exact moment, stored as UTC, shown in the session's time zone | Almost every "when did it happen" column |
timestamp (without time zone) | A date and clock time with no zone | Rarely right; ambiguous across time zones |
interval | A duration | INTERVAL '14 days', INTERVAL '1 month' |
SELECT id, ordered_at::text,
(ordered_at + 14)::text AS return_by,
EXTRACT(DOW FROM ordered_at) AS dow
FROM orders WHERE id IN (101, 104);| id | ordered_at | return_by | dow |
|---|---|---|---|
| 101 | 2026-06-01 | 2026-06-15 | 1 |
| 104 | 2026-07-02 | 2026-07-16 | 4 |
date + integeradds days.EXTRACT(DOW ...)gives the day of week (0 = Sunday, so 1 is Monday).DATE '2026-08-01' - DATE '2026-06-01'gives 61 (days).date_trunc('month', ordered_at)rounds down to the first of the month, for grouping:
SELECT date_trunc('month', ordered_at)::date AS month, COUNT(*) AS orders
FROM orders GROUP BY 1 ORDER BY 1;| month | orders |
|---|---|
| 2026-06-01 | 3 |
| 2026-07-01 | 2 |
| 2026-08-01 | 1 |
Date ranges: use half-open intervals
"All orders in July":
SELECT id FROM orders WHERE ordered_at >= DATE '2026-07-01' AND ordered_at < DATE '2026-08-01';| id |
|---|
| 104 |
| 105 |
Use >= start AND < next start. BETWEEN '2026-07-01' AND '2026-07-31' misses most of 31 July when the column is a timestamp (it only includes midnight). Also avoid wrapping the column in a function (WHERE date_trunc('month', ordered_at) = ...), which prevents index use (Lesson 220).
Time zones
Store UTC (timestamptz), convert for display:
SELECT ('2026-11-23 16:00:00+00'::timestamptz AT TIME ZONE 'Europe/London')::text AS winter,
('2026-07-23 16:00:00+00'::timestamptz AT TIME ZONE 'Europe/London')::text AS summer;| winter | summer |
|---|---|
| 2026-11-23 16:00:00 | 2026-07-23 17:00:00 |
The same 16:00 UTC is 16:00 in London in winter (GMT) but 17:00 in summer (BST). Use IANA zone names like Europe/London, never fixed offsets like +01:00, so daylight saving is handled. "Daily" reports must say whose day: midnight in London is not midnight in UTC during summer.
How to say it in an interview
"NULL means unknown, so comparisons with it are unknown rather than true or false; I use IS NULL, COALESCE for defaults, NULLIF to avoid division by zero and IS DISTINCT FROM for NULL-safe comparison, and I remember that WHERE drops unknown rows and NOT IN breaks with NULLs. CASE gives conditional values and works inside aggregates. For time I store timestamptz in UTC, convert with AT TIME ZONE using IANA names for display, query ranges as greater-or-equal start and less-than next start, and avoid wrapping indexed columns in functions."
Key words
| Word | Meaning |
|---|---|
| NULL | Unknown or missing value |
| Three-valued logic | TRUE, FALSE and UNKNOWN |
| COALESCE | First non-NULL value |
| NULLIF | NULL if two values are equal |
| IS DISTINCT FROM | NULL-safe inequality |
| CASE | Conditional expression |
| timestamptz | A moment in time stored as UTC |
| Half-open range | Includes the start, excludes the end |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.