Subqueries help you write powerful queries inside other queries. They're useful when you need intermediate results.
1๏ธโฃ What is a Subquery?
A subquery is a query inside
() that runs first and passes its result to the outer query.Example: Get employees who earn above average salary.
SELECT name, salaryโ Subquery calculates average salary โ main query finds those above it.
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
2๏ธโฃ Subquery in SELECT Clause
You can use subqueries to return values in each row.
Example: Show employee names with department name.
SELECT name,3๏ธโฃ Subquery in FROM Clause
(SELECT dept_name FROM departments d WHERE d.id = e.dept_id) AS department
FROM employees e;
Use when you want to filter or group temporary results.
Example: Get department-wise highest salary.
SELECT dept_id, MAX(salary)4๏ธโฃ Correlated Subquery
FROM (SELECT * FROM employees WHERE active = 1) AS active_emps
GROUP BY dept_id;
A subquery that uses a value from the outer query row.
Example: Get employees with highest salary in their department.
SELECT name, salaryโ Subquery runs for each row using outer query value.
FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees WHERE dept_id = e.dept_id);
๐ก Real Use Cases:
โข Filter rows based on dynamic conditions
โข Compare values across groups
โข Fetch related info in SELECT
๐ฏ Practice Tasks:
โข Write a query to find 2nd highest salary
โข Use subquery to get customers who placed more than 3 orders
โข Create a nested query to show top-selling product per category
โ Solution for Practice Tasks ๐
1๏ธโฃ Find 2nd Highest Salary
SELECT MAX(salary) AS second_highest_salaryโถ๏ธ Finds the highest salary less than the max salary โ gives the 2nd highest.
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
2๏ธโฃ Customers Who Placed More Than 3 Orders
SELECT customer_idโถ๏ธ Groups orders by customer and filters those with more than 3.
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) > 3;
You can join to get customer names:
SELECT name3๏ธโฃ Top-Selling Product Per Category
FROM customers
WHERE id IN (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) > 3
);
SELECT p.name, p.category_id, p.salesโถ๏ธ Correlated subquery finds the highest sales within each category.
FROM products p
WHERE p.sales = (
SELECT MAX(sales)
FROM products
WHERE category_id = p.category_id
);
๐ฌ Tap โค๏ธ for more!