A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

4.6 Subqueries


Subqueries in SQL are queries embedded within another query. They can be used to retrieve data that will be used in the main query's condition. Subqueries can appear in various clauses such as SELECT, FROM, and WHERE. Let's explore some examples:

4.6.1 Basic Subquery

Consider the following scenario where you want to find employees in the "Employees" table who have salaries greater than the average salary:

SELECT EmployeeID, FirstName, LastName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

EmployeeIDFirstNameLastNameSalary
2JaneDoe60000
4JohnSmith70000
5MaryJohnson80000

In this example, the subquery (SELECT AVG(Salary) FROM Employees) calculates the average salary, and the main query retrieves employees with salaries greater than that average.

4.6.2 Correlated Subquery

A correlated subquery refers to a subquery that depends on the outer query. Let's find employees whose salaries are higher than the average salary in their department:

SELECT EmployeeID, FirstName, LastName, DepartmentID, Salary
FROM Employees e
WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = e.DepartmentID);

EmployeeIDFirstNameLastNameDepartmentIDSalary
4JohnSmith170000
5MaryJohnson180000
8MichaelBrown275000
9JessicaDavis282000

Here, the subquery compares salaries within the same department by using the correlated condition WHERE DepartmentID = e.DepartmentID.

4.6.3 Subquery in FROM Clause

Subqueries can also appear in the FROM clause, creating a derived table. Let's find the total sales per employee:

SELECT e.EmployeeID, e.FirstName, e.LastName, TotalSales
FROM Employees e
JOIN (SELECT EmployeeID, SUM(SalesAmount) AS TotalSales FROM Sales GROUP BY EmployeeID) s
ON e.EmployeeID = s.EmployeeID;

EmployeeIDFirstNameLastNameTotalSales
1JohnDoe95000
2JaneDoe120000
3BobJohnson80000
4JohnSmith110000
5MaryJohnson90000
6EmilyDavis75000
7JamesWilson60000
8MichaelBrown100000
9JessicaDavis85000

This example shows a subquery in the FROM clause, creating a derived table (aliased as s) to calculate the total sales per employee.

Feel free to execute these queries in your SQL environment to see the results. Subqueries are powerful tools for creating flexible and dynamic SQL queries.