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.
Scalar subqueries let you use a small query inside another query to get a single value. This helps you compare or calculate values easily.
SELECT column1, (SELECT single_value FROM table2 WHERE condition) AS alias_name FROM table1 WHERE condition;
SELECT name, (SELECT MAX(score) FROM scores) AS max_score FROM players;
SELECT employee_id, salary, (SELECT AVG(salary) FROM employees) AS avg_salary FROM employees;
SELECT product_name, price, (SELECT discount FROM discounts WHERE product_id = products.id LIMIT 1) AS discount FROM products;
This query lists each employee's name and salary, and uses a scalar subquery to find the department name for each employee.
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;
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.
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.
students(id, name)scores(student_id, score)SELECT name, (SELECT AVG(score) FROM scores WHERE student_id = students.id) AS avg_score FROM students;
SELECT name, (SELECT score FROM scores) AS score FROM students;
Pass the test and this pattern moves unknown