What if you could get detailed answers from your data with just one simple question?
Why Scalar subquery in SELECT in SQL? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a big table of sales data and you want to find each salesperson's total sales along with their highest single sale. Doing this by hand means opening many sheets, adding numbers one by one, and trying to match totals with highest sales manually.
Manually calculating totals and highest sales is slow and easy to mess up. You might add wrong numbers or miss some sales. It's hard to keep track and update when new data arrives. This wastes time and causes mistakes.
A scalar subquery in SELECT lets you ask the database to find one single value for each row, like the highest sale for a salesperson, right next to their total sales. It does all the math inside the query, so you get accurate results fast and easy.
SELECT salesperson, SUM(sale_amount) FROM sales GROUP BY salesperson;
-- Then separately find max sale per person and join manuallySELECT salesperson, SUM(sale_amount),
(SELECT MAX(sale_amount) FROM sales s2 WHERE s2.salesperson = s1.salesperson) AS max_sale
FROM sales s1
GROUP BY salesperson;This lets you combine summary data and detailed calculations in one simple query, making your reports smarter and faster.
A store manager can quickly see each employee's total sales and their biggest sale in one report, helping to reward top performers without extra work.
Manual calculations are slow and error-prone.
Scalar subqueries get single values per row inside SELECT.
This makes complex reports easy and accurate.
Practice
SELECT clause return?Solution
Step 1: Understand scalar subquery definition
A scalar subquery returns exactly one value, meaning one row and one column.Step 2: Compare with other subquery types
Unlike table subqueries, scalar subqueries cannot return multiple rows or columns.Final Answer:
A single value (one row, one column) -> Option CQuick Check:
Scalar subquery = single value [OK]
- Thinking scalar subquery returns multiple rows
- Confusing scalar subquery with table subquery
- Assuming scalar subquery returns column names only
SELECT clause?Solution
Step 1: Identify correct scalar subquery syntax
The scalar subquery must be enclosed in parentheses and used inside the SELECT clause.Step 2: Check each option
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; correctly uses parentheses around the subquery. Others miss parentheses or have wrong placement.Final Answer:
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; -> Option BQuick Check:
Scalar subquery syntax = parentheses [OK]
- Omitting parentheses around subquery
- Placing SELECT keyword incorrectly
- Using aggregate functions without subquery
employees(id, name, dept_id) and departments(id, dept_name), what is the output of this query?SELECT name, (SELECT dept_name FROM departments WHERE id = employees.dept_id) AS department FROM employees ORDER BY name;
Solution
Step 1: Understand query logic
For each employee, the scalar subquery fetches the department name matching their dept_id.Step 2: Match employees to departments
Alice's dept_id matches HR, Bob's matches IT, so the output shows correct department names.Final Answer:
[{"name": "Alice", "department": "HR"}, {"name": "Bob", "department": "IT"}] -> Option DQuick Check:
Scalar subquery returns matching department name per employee [OK]
- Assuming subquery returns multiple rows causing error
- Mixing up department names for employees
- Expecting nulls when matching keys exist
SELECT name, (SELECT dept_name FROM departments WHERE id = employees.dept_id) AS department FROM employees WHERE (SELECT COUNT(*) FROM departments) > 0;
Solution
Step 1: Analyze subquery in WHERE clause
The subquery in WHERE returns COUNT(*), which is a single value, so it's valid.Step 2: Consider efficiency and logic
Using a scalar subquery in WHERE like this works but is inefficient; better to check existence differently.Final Answer:
Scalar subquery in WHERE is valid but inefficient -> Option AQuick Check:
Scalar subquery in WHERE can be valid but watch efficiency [OK]
- Thinking scalar subquery in WHERE always causes error
- Confusing alias requirement in SELECT with WHERE
- Assuming subquery returns multiple rows here
Options:
A) SELECT product_name, IFNULL((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products WHERE category_id IS NOT NULL;
B) SELECT product_name, (SELECT category_name FROM categories WHERE id = products.category_id) OR 'Uncategorized' AS category FROM products;
C) SELECT product_name, (SELECT category_name FROM categories WHERE id = products.category_id) AS category FROM products WHERE category_id IS NOT NULL;
D) SELECT product_name, COALESCE((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products;
Solution
Step 1: Handle NULL category_id with scalar subquery
Use COALESCE to replace NULL result from subquery with 'Uncategorized'.Step 2: Check each option's correctness
The query with COALESCE((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products; correctly uses COALESCE and includes all products. The query with (SELECT category_name FROM categories WHERE id = products.category_id) OR 'Uncategorized' uses invalid OR syntax. The queries with WHERE category_id IS NOT NULL exclude products with NULL category_id.Final Answer:
SELECT product_name, COALESCE((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products; -> Option AQuick Check:
Use COALESCE with scalar subquery for NULL handling [OK]
- Using OR instead of COALESCE or IFNULL
- Filtering out NULL category_id rows
- Not handling NULL results from subquery
