COALESCE Function in SQL

Level 370 keystrokes

COALESCE returns the first non-NULL value in the list.

SQL code

-- Return each user's name and phone number
1SELECT
2 name,
-- COALESCE returns the first non-NULL argument, checked from left to right
-- So a missing phone (NULL) is shown as 'N/A', like Bob's
3 COALESCE(phone, 'N/A') AS phone
4FROM
5 users
-- Sort the rows alphabetically by name
6ORDER BY
7 name;

Output

+-------+--------------+
| name  | phone        |
+-------+--------------+
| Alice | 123-456-7890 |
| Bob   | N/A          |
| Carol | 555-123-4567 |
+-------+--------------+
3 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • ,× 2
  • '× 2
  • ;× 1
  • (× 1
  • )× 1
  • /× 1

More SQL examples at level 3

← SQL typing practice