Learn Correlated & Non-Correlated Subqueries in SELECT, FROM, WHERE - Textnotes

Learn Correlated & Non-Correlated Subqueries in SELECT, FROM, WHERE


Master SQL subqueries in this beginner-friendly guide. Learn how to use subqueries in SELECT, FROM, and WHERE clauses, and understand correlated vs non-correlated subqueries. Practice finding employees earning more than average and customers with highest purchases.

1. Introduction

A subquery (or inner query) is a query inside another SQL query.

  1. Subqueries are used to fetch intermediate results for filtering, aggregation, or calculations.
  2. They can appear in SELECT, FROM, or WHERE clauses.

Key Points:

  1. Subqueries improve query flexibility.
  2. Can be single-row, multi-row, or multi-column.
  3. Can be correlated (depends on outer query) or non-correlated (independent).

2. Subqueries in SELECT, FROM, WHERE

2.1 Subquery in WHERE Clause

  1. Filters rows based on a condition calculated by the subquery.

Example:


-- Employees earning more than average salary
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

2.2 Subquery in FROM Clause

  1. Treats the subquery result as a temporary table.

Example:


-- Average salary per department using subquery
SELECT Department, AvgSalary
FROM (SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department) AS DeptAvg
WHERE AvgSalary > 50000;

2.3 Subquery in SELECT Clause

  1. Calculates a value for each row in the outer query.

Example:


-- Display employee name with department average salary
SELECT Name,
(SELECT AVG(Salary)
FROM Employees e2
WHERE e2.Department = e1.Department) AS DeptAvgSalary
FROM Employees e1;

3. Correlated vs Non-Correlated Subqueries

TypeDescriptionExample
Non-CorrelatedIndependent subquery(SELECT AVG(Salary) FROM Employees)
CorrelatedDepends on outer query row(SELECT AVG(Salary) FROM Employees e2 WHERE e2.Department = e1.Department)

Key:

  1. Correlated subqueries execute once per row of outer query.
  2. Non-correlated subqueries execute once independently.

4. Practical Exercises

  1. List employees earning more than the average salary.
  2. Find customers with the highest purchase amount.
  3. Retrieve products priced above the category average.
  4. Display employees whose salary is above department average.
  5. Count orders where the order quantity exceeds the average order quantity.

5. Tips for Beginners

  1. Start with non-correlated subqueries to understand the concept.
  2. Use aliases for subquery tables for clarity.
  3. Use IN, ANY, or ALL operators with subqueries for advanced filtering.
  4. Combine subqueries with joins for complex queries.


Next Step: After mastering subqueries, the next module is Set Operations, where you’ll learn UNION, UNION ALL, INTERSECT, and EXCEPT/MINUS for combining query results.