COALESCE Function in SQL

Level 4114 keystrokes

COALESCE returns the first non-NULL value from its arguments, here the best available contact.

SQL code

-- Return each customer's name and one way to contact them
1SELECT
2 name,
-- Use phone if it is not NULL, else email, else the text 'No contact'
3 COALESCE(phone, email, 'No contact') AS contact
4FROM
5 customers
-- Only active customers
6WHERE
7 status = 'active'
-- Sort the rows alphabetically by name
8ORDER BY
9 name;

Output

+-------+-----------------+
| name  | contact         |
+-------+-----------------+
| Alice | 555-1234        |
| Bob   | bob@example.com |
| Carol | No contact      |
+-------+-----------------+
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.

  • '× 4
  • ,× 3
  • ;× 1
  • (× 1
  • )× 1
  • =× 1

More SQL examples at level 4

← SQL typing practice