SQL beginner COALESCE NULL handling default values ANSI SQL

SQL COALESCE: Handle NULLs Gracefully

COALESCE Function is a SQL query that coalesce checks each argument left to right. Formula Genius generates and validates this formula automatically from a plain-English prompt.

COALESCE returns the first non-NULL value from a list. Essential for default values, NULL-safe calculations, and clean query output.

The Formula

Prompt

"Show the customer's nickname if available, otherwise their first name, otherwise 'Unknown'"

SQL
SELECT COALESCE(nickname, first_name, 'Unknown') AS display_name
FROM customers;

COALESCE checks each argument left to right. If nickname is NULL, it tries first_name. If that's also NULL, it returns 'Unknown'. The first non-NULL value wins.

Step-by-Step Breakdown

  1. COALESCE(value1, value2, ..., default) returns first non-NULL
  2. nickname is checked first — used if not NULL
  3. first_name is the fallback if nickname is NULL
  4. 'Unknown' is the final default if both are NULL
  5. Works with any data type: text, numbers, dates

Edge Cases & Warnings

  • Empty string ('') is NOT NULL — COALESCE won't skip it
  • All arguments should be the same data type or implicitly castable
  • COALESCE is standard SQL — works in PostgreSQL, MySQL, SQL Server, SQLite, Oracle
  • COALESCE(a, b) is equivalent to CASE WHEN a IS NOT NULL THEN a ELSE b END

Examples

Prompt

"nickname: 'Johnny', first_name: 'John'"

SQL
Johnny
Prompt

"nickname: NULL, first_name: 'John'"

SQL
John
Prompt

"nickname: NULL, first_name: NULL"

SQL
Unknown

Frequently Asked Questions

What's the difference between COALESCE and IFNULL?

IFNULL takes exactly 2 arguments and is MySQL-specific. COALESCE takes any number of arguments and is ANSI SQL standard. Always prefer COALESCE for portability.

How do I handle NULLs in calculations?

Wrap columns: COALESCE(amount, 0) ensures NULL amounts become 0 in SUM/AVG calculations. NULL + anything = NULL without COALESCE.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.