Scalar subqueries are one of the most powerful and frequently used features of SQL. They allow for embedding queries within other queries to fetch a single value.
A scalar subquery is a subquery that returns exactly one value (one row with one column). This single value can then be used as an input for other parts of an SQL query, such as in a SELECT list, a WHERE clause, or even within expressions.
Scalar subqueries are essential for:
The syntax of scalar subqueries is straightforward:
SELECT column1, (SELECT single_value_column FROM table WHERE condition) AS alias
FROM main_table;
MAX
, MIN
, or AVG
are used.Scalar subqueries can be used to calculate values dynamically in the SELECT statement.
SELECT name,
(SELECT AVG(salary) FROM employees) AS avg_salary
FROM employees;
Name | Salary |
---|---|
Alice | 70000 |
John | 80000 |
Scalar subqueries can provide values for new rows.
INSERT INTO high_earners (name, salary)
VALUES ('Alice', (SELECT MAX(salary) FROM employees));
high_earners
table with that salary.Update values dynamically using scalar subqueries.
UPDATE employees
SET bonus = (SELECT AVG(bonus) FROM employees)
WHERE department_id = 101;
Filter rows to delete based on scalar subquery conditions.
DELETE FROM employees
WHERE salary < (SELECT MIN(salary) FROM employees WHERE department_id = 102);
SELECT name,
(SELECT 'Manager' FROM dual) AS role
FROM employees;
Name | Role |
---|---|
Alice | Manager |
Bob | Manager |
SELECT name,
(SELECT MAX(salary)
FROM employees
WHERE department_id = (SELECT department_id
FROM departments
WHERE name = 'HR')) AS max_salary_in_hr
FROM employees;
Name | Max_Salary_in_HR |
---|---|
Alice | 90000 |
Bob | 90000 |
Aspect | Scalar Subqueries | Regular Subqueries |
---|---|---|
Output | One row, one column | Can return multiple rows or columns |
Usage | SELECT, WHERE, INSERT, UPDATE, DELETE | Primarily in FROM or WHERE clauses |
Complexity | Simple to intermediate | Suitable for more complex operations |
Multiple Rows Returned: If the subquery returns more than one row, it results in an error.
Solution: Use aggregate functions like MAX
, MIN
, or AVG
.
Performance Issues: Repeated scalar subquery execution can slow down queries.
Solution: Optimize the query or consider joins when applicable.
Scalar subqueries are a versatile feature in SQL, allowing dynamic and efficient data retrieval. They simplify query writing and make it possible to handle complex scenarios with minimal effort. By mastering scalar subqueries, you can elevate your SQL skills and handle a wide range of real-world database challenges. Happy Coding!❤️