JournalSQLFunctions and dates2 min
For Those Who Do Not Know COALESCE
The COALESCE function handles empty (NULL) values.
- COALESCE
- NULL
- default value
What Is the COALESCE() Function?
The COALESCE function handles empty (NULL) values.
Specifically, it returns the first argument or column whose value is not NULL (not empty).
The definition of this function in the documentation:
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null.
Syntax of COALESCE
COALESCE(value [, ...])That means we can pass one or more values into it, and as we said, it will return the first non-NULL value.
Why Do We Use It?
Mostly, we use it to return a default value instead of leaving values empty (NULL).
Example:
If we write:
SELECT COALESCE(NULL, NULL, 1, NULL, 2)The output will return the first non-NULL value:
1And if we write:
SELECT COALESCE(NULL, NULL, NULL)The output will be:
NULLAnd this is the only case where COALESCE will return NULL: when all the values are NULL.
Let's Look at a More Realistic Example
game_consoles Table
Suppose we have a video game consoles database. Reference: https://www.finder.com.au/2017-exclusives-comparison-ps4-xbox-one-switch
games Table
Example:
If I ask you to display the exclusive games for video game consoles, you would write:
SELECT g.name AS game, gc.name AS exclusive_console
FROM games AS g
JOIN game_consoles AS gc
ON g.exclusive_for = gc.idThe output will be:
Notice that 3 games did not appear (FIFA 18, PES 2018, Battlefield 1). That is because those games run on all game consoles.
Therefore, we want to display them, so we use LEFT JOIN:
SELECT g.name AS game, gc.name AS exclusive_console
FROM games AS g
LEFT JOIN game_consoles AS gc
ON g.exclusive_for = gc.idAnd the output will be:
If we want to display a default value instead of empty values to clarify that these games run on all consoles (not just one console), we write:
SELECT g.name AS game, COALESCE(gc.name, 'Available for all') AS exclusive_console
FROM games AS g
LEFT JOIN game_consoles AS gc
ON g.exclusive_for = gc.idAnd the expected output will be: