AI Hints
Home›PostgreSQL Tutorial›Querying Rows
PostgreSQL · Lesson 9 of 120

NULL and COALESCE

Missing values.

⏱ 2 min read▶ Video at 7:01🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Some customers never gave a city. That's not an empty string, it's null, meaning unknown. Null behaves differently from every other value.

  • No city given
  • NULL = unknown
  • Special rules

Finding NULLs

Equals null never matches anything, so we use is null. Coalesce replaces null with a fallback value. Run it. Customers without a city, shown as unknown.

query.sqlsql
SELECT first_name, coalesce(city, 'unknown') AS city
FROM customers
WHERE city IS NULL
LIMIT 3;
Output
 first_name |  city
------------+---------
 Hugo       | unknown
 Priya      | unknown
 Will       | unknown
(3 rows)

NULL rules

Anything compared with null gives null, not true. Count of a column skips nulls. Is distinct from treats two nulls as equal. And null sorts last when ascending, unless you say nulls first.

keyvalue
NULL = NULLnull, not true
count(col)skips nulls
IS DISTINCT FROMnull-safe compare
NULLS FIRSTcontrol sorting

Summary

Null means unknown, so test it with is null, and replace it with coalesce. Next, number types.

Key takeaways
  • IS NULL
  • COALESCE
  • Unknown
Next up: Numbers: integer, numeric, double — pick the right one