Subqueries in the FROM clause, also known as derived tables, are a powerful SQL feature that allows you to use the result of a subquery as a temporary table within your main query. This technique can simplify complex queries and improve query performance in certain scenarios.
When you use a subquery in the FROM clause, you're essentially creating a virtual table that exists only for the duration of the query. This derived table can be treated like any other table in your main query, allowing you to join it with other tables or apply additional filtering and aggregation.
The basic syntax for using a subquery in the FROM clause is as follows:
SELECT column1, column2, ...
FROM (SELECT ... FROM ...) AS derived_table
WHERE condition;
Note that you must always provide an alias for the derived table using the AS keyword.
Subqueries in FROM can help break down complex queries into more manageable parts. Consider this example:
SELECT department, avg_salary
FROM (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
) AS dept_averages
WHERE avg_salary > 50000;
This query first calculates the average salary for each department, then filters the results to show only departments with an average salary above 50,000.
Subqueries in FROM are particularly useful when you need to join aggregated data with the original table:
SELECT e.employee_name, e.salary, d.avg_salary
FROM employees e
JOIN (
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
) AS d ON e.department = d.department
WHERE e.salary > d.avg_salary;
This query identifies employees whose salary is above their department's average.
To further enhance your understanding of SQL subqueries, explore these related topics:
By mastering subqueries in the FROM clause, you'll be able to write more efficient and flexible SQL queries, handling complex data transformations with ease.