Welcome to our SQL Subqueries tutorial! In this lesson, we'll explore a powerful feature of SQL that allows you to nest one SELECT statement within another. Let's dive in! 🤿
Subqueries are SELECT statements nested within other SQL statements like SELECT, INSERT, UPDATE, or DELETE. They are used to reuse the result set of one query as input to another query.
Let's take a simple example to understand this better. Suppose you want to find out the average salary of employees who work in the department with the highest average salary.
The basic syntax for a subquery is as follows:
SELECT column_list
FROM table_name
WHERE column_name = (Subquery);The subquery is enclosed within parentheses () and returns a single value (for equality comparison) or a list of values (for IN, ANY, ALL, etc. comparison).
Let's create a simple table for this example:
CREATE TABLE Employees (
ID INT PRIMARY KEY,
DepartmentID INT,
Salary INT,
Name VARCHAR(50)
);
INSERT INTO Employees VALUES
(1, 101, 5000, 'John'),
(2, 101, 5500, 'Jane'),
(3, 102, 4000, 'Doe'),
(4, 102, 4500, 'Alice');Now, let's find the name of the employee who has the highest salary:
SELECT Name
FROM Employees
WHERE Salary = (
SELECT MAX(Salary) FROM Employees
);A correlated subquery is a subquery that references a column from the main query. The subquery is executed once for each row of the main query.
Let's find the average salary of each department:
SELECT DepartmentID, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY DepartmentID;Now, let's find the department with the highest average salary:
SELECT DepartmentID, AVG(Salary) AS AverageSalary
FROM Employees
WHERE Salary = (
SELECT AVG(Salary) FROM Employees
WHERE DepartmentID = Employees.DepartmentID
);SELECT *
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
WHERE DepartmentID = Employees.DepartmentID
);SELECT *
FROM Departments
WHERE EXISTS (
SELECT *
FROM Employees
WHERE Employees.DepartmentID = Departments.ID AND Salary > 5000
);Which SQL statement allows you to nest one SELECT statement within another?
What is a correlated subquery?