๐ฅ Now, letโs move to the next topic of SQL Roadmap
โ
Subqueries (Nested Queries)
๐ง 1. What is a Subquery?
A subquery is a query inside another query
๐ Think like this:
โFirst get some data โ then use that result in another queryโ
๐ Basic Example
๐ Find employees earning above average salary
SELECT FROM employees
WHERE salary > (
SELECT AVG(salary) FROM employees
);
๐ Inner query โ gives average salary
๐ Outer query โ filters employees
โก 2. Types of Subqueries
๐น Single Row Subquery
Returns only one value
SELECT FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
๐น Multiple Row Subquery
Returns multiple values
SELECT FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments
);
๐ฏ 3. Subquery with IN
SELECT name
FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments WHERE dept_name = 'IT'
);
โ Finds employees in IT department
โก 4. Subquery with EXISTS
SELECT name
FROM employees e
WHERE EXISTS (
SELECT 1 FROM departments d
WHERE e.dept_id = d.dept_id
);
โ Checks if matching record exists
๐จ 5. Important Difference
IN ->
Compares values & Slower with large data
EXISTS -> Checks existence & Faster with large data
๐ฏ 6. Practice Tasks
1. Find employees with salary > average salary
2. Find employees in IT department using subquery
3. Get departments that have employees
4. Find employees with max salary
5. Get employees not in HR department
๐ฅ Here are the solutions for Subqueries practice tasks
โ
1. Find employees with salary > average salary
SELECT FROM employees
WHERE salary > (
SELECT AVG(salary) FROM employees
);
โ
2. Find employees in IT department using subquery
SELECT FROM employees
WHERE dept_id IN (
SELECT dept_id FROM departments
WHERE dept_name = 'IT'
);
โ
3. Get departments that have employees
SELECT FROM departments
WHERE dept_id IN (
SELECT dept_id FROM employees
);
๐ Alternative (using EXISTS):
SELECT FROM departments d
WHERE EXISTS (
SELECT 1 FROM employees e
WHERE d.dept_id = e.dept_id
);
โ
4. Find employees with max salary
SELECT FROM employees
WHERE salary = (
SELECT MAX(salary) FROM employees
);
โ
5. Get employees not in HR department
SELECT FROM employees
WHERE dept_id NOT IN (
SELECT dept_id FROM departments
WHERE dept_name = 'HR'
);
โก Mini Challenge ๐ฅ
๐ Find employees earning second highest salary using subquery
โก Mini Challenge Solution ๐ฅ
SELECT FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
WHERE salary < (
SELECT MAX(salary) FROM employees
)
);
๐ฅ Pro Tip:
If question says:
๐ โabove averageโ, โmaxโ, โsecond highestโ
โ Think Subquery instantly ๐ฏ
Double Tap โค๏ธ For More
Post #2746
8.28K
- โค 16