Home >Database >Mysql Tutorial >Understanding SQL Subqueries: A Complete Guide with Examples
A subquery, also known as an inner query or nested query, is a query within another SQL query. It is enclosed within parentheses and is executed first to provide results that the outer query uses for further processing.
Example:
Find the name of the employee with the highest salary:
SELECT Name FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
Example:
Find employees who work in departments with more than 5 members:
SELECT Name FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Members > 5);
Example:
Find employees earning more than the average salary of their department:
SELECT Name, Salary FROM Employees E WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = E.DepartmentID);
Example:
Find departments where the average employee salary exceeds $50,000:
SELECT Name FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
SELECT Name FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Members > 5);
SELECT Name, Salary FROM Employees E WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = E.DepartmentID);
SELECT DepartmentName FROM Departments WHERE DepartmentID IN ( SELECT DepartmentID FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees) );
SELECT * FROM Products WHERE Price > (SELECT AVG(Price) FROM Products);
Subqueries are a powerful tool in SQL for breaking down complex logic into manageable parts, enabling dynamic data analysis, and facilitating data manipulation. However, understanding when to use subqueries versus alternatives like joins is critical for optimal query performance.
The above is the detailed content of Understanding SQL Subqueries: A Complete Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!