Skip to the content

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:

SQL
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;
equalsis_nullplusconcatnullif_result
NULLtrueNULLNULLNULL

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) and NOT IN with a NULL returns nothing (Lesson 217).

Handling NULLs

SQL
SELECT name, COALESCE(city, 'Unknown') AS city FROM customers ORDER BY id;
namecity
Aisha KhanLondon
Ben SmithLeeds
Chen LiLondon
Dara PatelUnknown
Eve JonesManchester
ToolMeaning
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 bA NULL-safe "not equal": treats NULL as a comparable value
SQL
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 (AVG of 10, NULL, 20 is 15), except COUNT(*).
  • 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 DISTINCT to allow only one.
  • Design: use NOT NULL wherever 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:

SQL
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;
nameprice_penceband
Notebook450budget
Mug899budget
Pen Set1250standard
Desk Lamp2999standard
Kettle3499premium

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

TypeHoldsUse
dateA calendar dayBirthdays, order dates
timestamptzAn exact moment, stored as UTC, shown in the session's time zoneAlmost every "when did it happen" column
timestamp (without time zone)A date and clock time with no zoneRarely right; ambiguous across time zones
intervalA durationINTERVAL '14 days', INTERVAL '1 month'
SQL
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);
idordered_atreturn_bydow
1012026-06-012026-06-151
1042026-07-022026-07-164
  • date + integer adds 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:
SQL
SELECT date_trunc('month', ordered_at)::date AS month, COUNT(*) AS orders
FROM orders GROUP BY 1 ORDER BY 1;
monthorders
2026-06-013
2026-07-012
2026-08-011

Date ranges: use half-open intervals

"All orders in July":

SQL
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:

SQL
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;
wintersummer
2026-11-23 16:00:002026-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

WordMeaning
NULLUnknown or missing value
Three-valued logicTRUE, FALSE and UNKNOWN
COALESCEFirst non-NULL value
NULLIFNULL if two values are equal
IS DISTINCT FROMNULL-safe inequality
CASEConditional expression
timestamptzA moment in time stored as UTC
Half-open rangeIncludes the start, excludes the end

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.