Challenge - 5 Problems
COALESCE and NULLIF Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of COALESCE with NULL values
Given the table Employees with columns
Assume the data:
id, name, and nickname, what is the output of this query?SELECT id, COALESCE(nickname, name) AS display_name FROM Employees ORDER BY id;
Assume the data:
id | name | nickname 1 | Alice | NULL 2 | Bob | Bobby 3 | Charlie | NULL
SQL
SELECT id, COALESCE(nickname, name) AS display_name FROM Employees ORDER BY id;
Attempts:
2 left
💡 Hint
COALESCE returns the first non-NULL value from its arguments.
✗ Incorrect
COALESCE(nickname, name) returns nickname if it is not NULL; otherwise, it returns name. For id=1 and 3, nickname is NULL, so name is used. For id=2, nickname is 'Bobby', so it is used.
❓ query_result
intermediate2:00remaining
Using NULLIF to avoid division by zero
Consider a table Sales with columns
Given data:
region, total_sales, and total_customers. What is the output of this query?SELECT region, total_sales / NULLIF(total_customers, 0) AS avg_sale_per_customer FROM Sales ORDER BY region;
Given data:
region | total_sales | total_customers East | 1000 | 10 West | 500 | 0 North | 750 | 15
SQL
SELECT region, total_sales / NULLIF(total_customers, 0) AS avg_sale_per_customer FROM Sales ORDER BY region;
Attempts:
2 left
💡 Hint
NULLIF returns NULL if the second argument matches the first, preventing division by zero.
✗ Incorrect
NULLIF(total_customers, 0) returns NULL when total_customers is 0, so division by zero is avoided and result is NULL for West region.
📝 Syntax
advanced2:00remaining
Identify the syntax error in COALESCE usage
Which of the following SQL statements will cause a syntax error?
Attempts:
2 left
💡 Hint
Check the commas separating arguments in COALESCE.
✗ Incorrect
Option D misses a comma between NULL and 'default', causing a syntax error.
🧠 Conceptual
advanced1:30remaining
Understanding NULLIF behavior
What is the result of the expression
NULLIF('abc', 'abc') in SQL?Attempts:
2 left
💡 Hint
NULLIF returns NULL if both arguments are equal.
✗ Incorrect
NULLIF returns NULL when both arguments are equal, otherwise returns the first argument.
❓ optimization
expert2:30remaining
Optimizing CASE with COALESCE
You want to replace this CASE statement with a simpler expression:
Which of the following is the best equivalent SQL expression?
SELECT CASE WHEN col1 IS NOT NULL THEN col1 ELSE col2 END AS result FROM table1;
Which of the following is the best equivalent SQL expression?
Attempts:
2 left
💡 Hint
COALESCE returns the first non-NULL value.
✗ Incorrect
COALESCE(col1, col2) returns col1 if it is not NULL, else col2, matching the CASE logic.