Introduction
Sometimes you want to use the result of one query as a temporary table inside another query. This helps break down complex questions into smaller parts.
Jump into concepts and practice - no test required
Sometimes you want to use the result of one query as a temporary table inside another query. This helps break down complex questions into smaller parts.
SELECT columns FROM (SELECT columns FROM table WHERE condition) AS alias WHERE outer_condition;
SELECT avg_salary FROM (SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department) AS dept_avg WHERE avg_salary > 50000;
SELECT name, total_sales FROM (SELECT customer_id, SUM(amount) AS total_sales FROM sales GROUP BY customer_id) AS sales_summary JOIN customers ON sales_summary.customer_id = customers.id WHERE total_sales > 1000;
This query finds departments where the average salary is more than 60,000 by using a subquery in the FROM clause.
SELECT department, avg_salary FROM (SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department) AS dept_avg WHERE avg_salary > 60000;
Always give your subquery an alias, or the database will give an error.
Subqueries in FROM can be used anywhere a table name is expected.
Using subqueries here can make complex queries easier to read and maintain.
Subqueries in the FROM clause create temporary tables for use in the main query.
They help break complex queries into smaller, understandable parts.
Always remember to give the subquery an alias.
subquery in the FROM clause in SQL?users(id, name)orders(id, user_id, amount)SELECT sub.name, sub.total FROM (SELECT u.name, SUM(o.amount) AS total FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name) AS sub WHERE sub.total > 100;
SELECT sub.name, sub.total FROM (SELECT name, SUM(amount) AS total FROM users JOIN orders ON users.id = orders.user_id) sub;