SQL · Module 4 · Lesson 51 min read

Working with NULL

What is NULL?

NULL means unknown or missing. It is not 0, not '' (empty string), and not false.

  • Hari's city is unknown → NULL
  • Maya's budget hasn't been set → NULL

⚠️ You can't compare with = NULL

Any comparison with NULL gives NULL (unknown), not true:

  • NULL = NULL → NULL
  • city = NULL → NULL for every row → no rows returned

✅ Use IS NULL and IS NOT NULL ✅ IS DISTINCT FROM / IS NOT DISTINCT FROM – comparisons that treat NULLs as equal values

NULL in calculations

  • Arithmetic with NULL → NULL: 100 + NULL = NULL
  • || concatenation with NULL → NULL (use concat(), which ignores NULLs)
  • Aggregates ignore NULLs: avg(monthly_budget) averages only known budgets; count(column) doesn't count NULLs (Unit 6)

NULL in sorting

PostgreSQL puts NULLs last in ascending order and first in descending order. Control it with NULLS FIRST / NULLS LAST.

Replacing NULLs

  • COALESCE(city, 'Unknown') – the first non-NULL value (Unit 5)
  • NULLIF(a, b) – returns NULL when a = b (e.g. to avoid dividing by zero)

Design advice

  • Use NOT NULL wherever a value is truly required
  • Decide what NULL means for each column ("not set yet" vs "not applicable") and document it
  • Don't store fake values like 'N/A' or -1 instead of NULL

Example

SQL
-- ❌ Returns nothing, even though Hari has no city
SELECT name FROM users WHERE city = NULL;

-- ✅ IS NULL / IS NOT NULL
SELECT name FROM users WHERE city IS NULL;              -- Hari Shrestha
SELECT name FROM users WHERE monthly_budget IS NULL;    -- Maya Karki
SELECT count(*) FROM expenses WHERE note IS NOT NULL;   -- 4

-- Comparisons with NULL are unknown
SELECT NULL = NULL          AS equals,          -- NULL
       NULL IS NULL         AS is_null,         -- true
       100 + NULL           AS math,            -- NULL
       'Hi ' || NULL        AS pipe_concat,     -- NULL
       concat('Hi ', NULL)  AS concat_fn;       -- 'Hi '

-- NULL-safe comparison
SELECT name FROM users WHERE city IS DISTINCT FROM 'Pokhara';
-- Asha, Sita, Bikash, Hari (Hari is included this time!)

-- Replace NULL for display
SELECT name,
       COALESCE(city, 'Unknown')            AS city,
       COALESCE(monthly_budget, 0)          AS budget
FROM users;

-- Sorting: control where NULLs go
SELECT name, monthly_budget FROM users ORDER BY monthly_budget DESC NULLS LAST;

-- Aggregates skip NULLs
SELECT count(*) AS all_users,              -- 6
       count(monthly_budget) AS with_budget, -- 5
       round(avg(monthly_budget)) AS avg_budget  -- 26000 (average of the 5 known budgets)
FROM users;