đ SQL Tutorial: Simple and Correlated Subqueries
Subqueries are queries inside other queries. They help you fetch data based on complex conditions.
đ Sample employees
Table:
employee_id | name | department_id | salary |
---|---|---|---|
1 | Arif | 101 | 50000 |
2 | Nasrin | 102 | 60000 |
3 | Rafi | 101 | 55000 |
4 | Ritu | 103 | 45000 |
5 | Faruk | 102 | 62000 |
1️⃣ Simple Subquery
Find employees who earn more than the average salary of all employees.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Output:
name | salary |
---|---|
Nasrin | 60000 |
Faruk | 62000 |
Rafi | 55000 |
2️⃣ Correlated Subquery
Find employees whose salary is greater than the average salary of their own department.
SELECT e1.name, e1.salary, e1.department_id
FROM employees e1
WHERE e1.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
Output:
name | salary | department_id |
---|---|---|
Rafi | 55000 | 101 |
Nasrin | 60000 | 102 |
Faruk | 62000 | 102 |
đ Summary:
- Simple Subquery: Independent query inside WHERE clause.
- Correlated Subquery: Subquery depends on outer query data.
- Correlated subqueries execute once per row of outer query.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ