DELAPARRA
Index
Color
NL
Category: SQL

COALESCE

Explained by Updated

What is COALESCE?

COALESCE: Returns the first non-NULL argument. The standard way to supply a default for NULL values. COALESCE returns the first value in its list that is not NULL. COALESCE(nickname, first_name, 'Guest') shows the nickname if there is one, otherwise the first name, otherwise the word Guest. It is the standard way to give NULL a sensible default in a query. That matters because NULL behaves unexpectedly in calculations and comparisons. price + NULL is NULL, and a SUM over a column full of nulls can return NULL instead of 0. COALESCE(SUM(amount), 0) fixes that.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about COALESCE

What should you keep in mind with COALESCE?

It works in every major SQL database, unlike vendor-specific functions such as IFNULL or NVL. Use it in reports and exports where empty values would confuse the reader. If a column should never be empty, a default value in the table definition is often the better fix.

What does an example of COALESCE look like?

SELECT COALESCE(nickname, name, 'Anonymous') AS display FROM users;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with C

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.