Problem
Task
Return each user's id and display name. Use nickname when it exists, otherwise use name.
Schema
Table Schema
users(id, name, nickname)
Input
Sample Data
| id | name | nickname |
|---|---|---|
| 1 | Alice | Al |
| 2 | Bob | NULL |
| 3 | Chloe | C |
Output
Expected Output
| id | display_name |
|---|---|
| 1 | Al |
| 2 | Bob |
| 3 | C |
Answer
Check Your Solution
Show Answer and Explanation
Correct Answer
SELECT id, COALESCE(nickname, name) AS display_name
FROM users
ORDER BY id;
Explanation
COALESCE returns the first non-NULL value. For Bob, nickname is NULL, so name is used as the fallback display value.
Common Mistakes
- Using nickname = NULL inside CASE conditions.
- Forgetting the alias display_name.
- Using an empty string fallback even when the problem asks to use name.
Concepts
Related Concepts
COALESCE
NULL Handling
Aliases
NULL
SELECT
Next practice