SQL Practice Problem #020

Show a fallback display name

Return each user's id and display name. Use nickname when it exists, otherwise use name.

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

idnamenickname
1AliceAl
2BobNULL
3ChloeC

Output

Expected Output

iddisplay_name
1Al
2Bob
3C

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

Related Problems