SQL Subqueries
What is a Subquery?
• - A subquery is a query within another query.
• - It can be used in SELECT, INSERT, UPDATE,
DELETE, or WHERE clauses.
Types of Subqueries
• - Single-row Subquery: Returns a single row of
data.
• - Multi-row Subquery: Returns multiple rows
of data.
• - Correlated Subquery: References a value
from the outer query.
• - Non-correlated Subquery: Independent of
the outer query.
Subqueries in SELECT, WHERE, and
FROM Clauses
• - SELECT Clause: SELECT column FROM table
WHERE column IN (SELECT ...);
• - WHERE Clause: SELECT * FROM table WHERE
column = (SELECT ...);
• - FROM Clause: SELECT * FROM (SELECT ...);
Benefits and Drawbacks of Using
Subqueries
• - Benefits: Simple, easy to read, and maintain.
• - Drawbacks: Can be inefficient for large data
sets, slower than joins.
Example of a Subquery in SQL
• Example:
• SELECT * FROM employees WHERE salary >
(SELECT AVG(salary) FROM employees);