Bird
Raised Fist0
MySQLquery~5 mins

Scalar subqueries in MySQL

Choose your learning style10 modes available
Introduction

Scalar subqueries let you use a small query inside another query to get a single value. This helps you compare or calculate values easily.

When you want to find a value from another table to use in a condition.
When you need to calculate a value on the fly for each row in your main query.
When you want to compare a column to a single value returned by another query.
When you want to add a calculated column based on a query result.
When you want to filter rows based on a single value from another query.
Syntax
MySQL
SELECT column1, (SELECT single_value FROM table2 WHERE condition) AS alias_name FROM table1 WHERE condition;
The subquery inside parentheses must return exactly one value (one row, one column).
If the subquery returns more than one value, MySQL will give an error.
Examples
This gets each player's name and the highest score from the scores table.
MySQL
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM players;
This shows each employee's salary and the average salary of all employees.
MySQL
SELECT employee_id, salary, (SELECT AVG(salary) FROM employees) AS avg_salary FROM employees;
This adds the discount for each product by looking it up in the discounts table.
MySQL
SELECT product_name, price, (SELECT discount FROM discounts WHERE product_id = products.id LIMIT 1) AS discount FROM products;
Sample Program

This query lists each employee's name and salary, and uses a scalar subquery to find the department name for each employee.

MySQL
CREATE TABLE employees (id INT, name VARCHAR(20), department_id INT, salary INT);
INSERT INTO employees VALUES (1, 'Alice', 10, 5000), (2, 'Bob', 20, 6000), (3, 'Charlie', 10, 5500);
CREATE TABLE departments (id INT, name VARCHAR(20));
INSERT INTO departments VALUES (10, 'Sales'), (20, 'HR');

SELECT name, salary, (SELECT name FROM departments WHERE id = employees.department_id) AS department_name FROM employees;
OutputSuccess
Important Notes

Scalar subqueries must return only one value. If they return zero rows, the result is NULL.

They are useful for adding extra info from another table without joining.

Summary

Scalar subqueries return a single value to use inside another query.

They help compare or add calculated values easily.

Make sure the subquery returns exactly one value to avoid errors.

Practice

(1/5)
1. What does a scalar subquery return in MySQL?
easy
A. A list of tables
B. A single value that can be used in another query
C. Only column names
D. Multiple rows and columns

Solution

  1. Step 1: Understand scalar subquery definition

    A scalar subquery returns exactly one value, not multiple rows or columns.
  2. Step 2: Identify usage in queries

    This single value can be used inside another query, like in WHERE or SELECT clauses.
  3. Final Answer:

    A single value that can be used in another query -> Option B
  4. Quick Check:

    Scalar subquery = single value [OK]
Hint: Scalar subqueries always return one value only [OK]
Common Mistakes:
  • Thinking scalar subqueries return multiple rows
  • Confusing scalar subqueries with table subqueries
  • Assuming scalar subqueries return column names only
2. Which of the following is the correct syntax for a scalar subquery in a SELECT statement?
easy
A. SELECT name, MAX(score) FROM scores FROM students;
B. SELECT name, MAX(score) AS max_score WHERE score > 50;
C. SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students;
D. SELECT name, (MAX(score) FROM scores) AS max_score FROM students;

Solution

  1. Step 1: Analyze correct scalar subquery syntax

    The scalar subquery must be enclosed in parentheses and return a single value, as in (SELECT MAX(score) FROM scores).
  2. Step 2: Check placement in SELECT clause

    SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; correctly places the scalar subquery inside the SELECT list with an alias.
  3. Final Answer:

    SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; -> Option C
  4. Quick Check:

    Scalar subquery syntax = SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM students; [OK]
Hint: Scalar subqueries must be in parentheses inside SELECT or WHERE [OK]
Common Mistakes:
  • Missing parentheses around subquery
  • Incorrect FROM clause placement
  • Using aggregate functions without subquery
3. Given the tables:
students(id, name)
scores(student_id, score)
What will this query return?
SELECT name, (SELECT AVG(score) FROM scores WHERE student_id = students.id) AS avg_score FROM students;
medium
A. Each student's name with their average score
B. The overall average score for all students repeated for each name
C. Syntax error due to subquery
D. List of student names only without scores

Solution

  1. Step 1: Understand the subquery correlation

    The subquery calculates the average score for each student by matching student_id with students.id.
  2. Step 2: Result of the main query

    The main query returns each student's name along with their individual average score from the subquery.
  3. Final Answer:

    Each student's name with their average score -> Option A
  4. Quick Check:

    Scalar subquery returns per-student average [OK]
Hint: Correlated scalar subqueries return values per row [OK]
Common Mistakes:
  • Assuming subquery returns overall average for all rows
  • Confusing correlated and uncorrelated subqueries
  • Expecting syntax error when none exists
4. Identify the error in this query using a scalar subquery:
SELECT name, (SELECT score FROM scores) AS score FROM students;
medium
A. No error, query runs fine
B. Missing alias for subquery
C. Incorrect table name in subquery
D. Subquery returns multiple rows causing an error

Solution

  1. Step 1: Analyze the subquery result

    The subquery SELECT score FROM scores returns multiple rows because no WHERE clause limits it.
  2. Step 2: Understand scalar subquery requirement

    Scalar subqueries must return exactly one value; multiple rows cause an error.
  3. Final Answer:

    Subquery returns multiple rows causing an error -> Option D
  4. Quick Check:

    Scalar subquery must return one value [OK]
Hint: Scalar subqueries must return one value, not many [OK]
Common Mistakes:
  • Ignoring multiple rows returned by subquery
  • Assuming alias is mandatory for subquery
  • Thinking query runs without error
5. You want to find students whose score is above the average score of all students. Which query correctly uses a scalar subquery to achieve this?
hard
A. SELECT name FROM students WHERE score > (SELECT AVG(score) FROM scores);
B. SELECT name FROM students WHERE score > SELECT AVG(score) FROM scores;
C. SELECT name FROM students WHERE (SELECT AVG(score) FROM scores) < (SELECT score FROM scores WHERE student_id = students.id);
D. SELECT name FROM students WHERE score > (SELECT score FROM scores);

Solution

  1. Step 1: Understand the goal

    We want students whose individual score is greater than the average score of all students.
  2. Step 2: Analyze each option

    SELECT name FROM students WHERE score > (SELECT AVG(score) FROM scores); correctly compares each student's score with the average score using a scalar subquery.
  3. Final Answer:

    SELECT name FROM students WHERE score > (SELECT AVG(score) FROM scores); -> Option A
  4. Quick Check:

    Scalar subquery compares average with individual score [OK]
Hint: Use scalar subquery for average, correlate for individual score [OK]
Common Mistakes:
  • Missing parentheses around subqueries
  • Using subquery without correlation for individual scores
  • Syntax errors from missing SELECT in WHERE
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard