Challenge - 5 Problems
COALESCE Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of COALESCE with multiple NULLs
Given the table Employees with columns
id, name, and bonus where some bonus values are NULL, what is the output of this query?SELECT id, COALESCE(bonus, 0) AS bonus_amount FROM Employees ORDER BY id;
SQL
CREATE TABLE Employees (id INT, name VARCHAR(20), bonus INT); INSERT INTO Employees VALUES (1, 'Alice', NULL), (2, 'Bob', 100), (3, 'Charlie', NULL);
Attempts:
2 left
💡 Hint
COALESCE returns the first non-NULL value from its arguments.
✗ Incorrect
The COALESCE function replaces NULL bonus values with 0, so rows with NULL bonus show 0 instead.
🧠 Conceptual
intermediate1:30remaining
Understanding COALESCE with multiple arguments
What will the following SQL expression return?
SELECT COALESCE(NULL, NULL, 'first non-null', 'second non-null');
Attempts:
2 left
💡 Hint
COALESCE returns the first argument that is not NULL.
✗ Incorrect
COALESCE checks each argument in order and returns the first one that is not NULL, which is 'first non-null'.
📝 Syntax
advanced1:30remaining
Identify the syntax error in COALESCE usage
Which option contains a syntax error when using COALESCE in SQL?
Attempts:
2 left
💡 Hint
Look for missing arguments or commas in the COALESCE function.
✗ Incorrect
Option C has two commas with no argument between them, causing a syntax error.
❓ query_result
advanced2:30remaining
COALESCE with different data types
Consider a table Orders with columns
Given data:
order_id, discount (INT), and coupon_code (VARCHAR). What is the output of this query?SELECT order_id, COALESCE(CAST(discount AS VARCHAR), coupon_code, 'No discount') AS discount_info FROM Orders ORDER BY order_id;
Given data:
order_id | discount | coupon_code 1 | NULL | 'SAVE10' 2 | 15 | NULL 3 | NULL | NULL
Attempts:
2 left
💡 Hint
COALESCE returns the first non-NULL value, casting discount to string to match coupon_code type.
✗ Incorrect
For order 1, discount is NULL, coupon_code is 'SAVE10', so returns 'SAVE10'. For order 2, discount is 15 (cast to '15'), so returns '15'. For order 3, both are NULL, so returns 'No discount'.
🔧 Debug
expert3:00remaining
Why does this COALESCE query return unexpected NULLs?
A developer wrote this query:
But the output shows NULL for some
SELECT user_id, COALESCE(last_login, 'Never') AS last_login_date FROM Users;
But the output shows NULL for some
last_login_date values even though last_login is NULL in those rows. What is the most likely cause?Attempts:
2 left
💡 Hint
Think about data types and how COALESCE returns a value matching the first argument's type.
✗ Incorrect
COALESCE returns a value with the type of the first argument. If last_login is DATE and 'Never' is a string, the database cannot convert 'Never' to DATE, so it returns NULL.