Subqueries in SELECT statements are a powerful feature in SQL that allow you to nest one query within another. They enable you to perform complex data retrieval operations and create more sophisticated queries.
A subquery in the SELECT clause, also known as a scalar subquery, returns a single value that can be used as a column in the result set. This technique is particularly useful when you need to include calculated values or data from related tables in your query results.
SELECT column1, column2,
(SELECT subquery_column FROM subquery_table WHERE condition) AS subquery_result
FROM main_table;
In this syntax, the subquery is enclosed in parentheses and placed in the SELECT list. It's often given an alias using the AS keyword for clarity.
SELECT
employee_id,
employee_name,
(SELECT department_name FROM departments WHERE departments.dept_id = employees.dept_id) AS department
FROM
employees;
This query retrieves the department name for each employee using a subquery in the SELECT clause.
SELECT
product_id,
product_name,
(SELECT AVG(price) FROM sales WHERE sales.product_id = products.product_id) AS avg_sale_price
FROM
products;
Here, we calculate the average sale price for each product using a subquery.
Mastering subqueries in SELECT statements enhances your SQL toolkit, allowing you to write more expressive and powerful queries. As you become more comfortable with this technique, you'll find numerous scenarios where it can simplify complex data retrieval tasks.