Challenge - 5 Problems
Scalar Subquery Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of scalar subquery in SELECT clause
What is the output of this query?
SELECT name, (SELECT MAX(score) FROM results WHERE results.user_id = users.id) AS max_score FROM users ORDER BY id;
PostgreSQL
CREATE TABLE users (id INT, name TEXT); CREATE TABLE results (user_id INT, score INT); INSERT INTO users VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO results VALUES (1, 50), (1, 70), (2, 40);
Attempts:
2 left
💡 Hint
Think about how the subquery filters results by user_id and finds the maximum score for each user.
✗ Incorrect
The scalar subquery finds the maximum score for each user by matching user_id. Alice has scores 50 and 70, max is 70. Bob has one score 40, max is 40.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in scalar subquery
Which option contains a syntax error in the scalar subquery usage?
PostgreSQL
SELECT name, (SELECT score FROM results WHERE user_id = users.id ORDER BY score DESC LIMIT 1) AS top_score FROM users;
Attempts:
2 left
💡 Hint
Check the order of clauses in the subquery.
✗ Incorrect
In SQL, LIMIT must come after ORDER BY. Option B places LIMIT before ORDER BY, causing a syntax error.
❓ optimization
advanced2:00remaining
Optimizing scalar subquery for performance
Which query is more efficient to get each user's highest score?
PostgreSQL
Tables: users(id, name), results(user_id, score)
Attempts:
2 left
💡 Hint
Consider how JOIN and GROUP BY can reduce repeated subquery executions.
✗ Incorrect
Option D uses a JOIN and GROUP BY to compute max scores in one pass, avoiding repeated scalar subqueries per user.
🧠 Conceptual
advanced2:00remaining
Understanding scalar subquery behavior with NULL results
What will be the output of this query if a user has no matching rows in results?
SELECT name, (SELECT MAX(score) FROM results WHERE user_id = users.id) AS max_score FROM users;
PostgreSQL
INSERT INTO users VALUES (3, 'Charlie'); -- Charlie has no results
Attempts:
2 left
💡 Hint
Think about what MAX returns when no rows match.
✗ Incorrect
MAX returns NULL when no rows match the condition, so max_score is NULL for Charlie.
🔧 Debug
expert3:00remaining
Debugging unexpected scalar subquery result
Why does this query return the same max_score for all users?
SELECT name, (SELECT MAX(score) FROM results) AS max_score FROM users;
PostgreSQL
Tables: users(id, name), results(user_id, score)
Attempts:
2 left
💡 Hint
Check if the subquery depends on the outer query row.
✗ Incorrect
The scalar subquery is uncorrelated; it returns the same max score for all users because it does not filter by user_id.