
Nest SELECT statements to create complex queries.
A subquery is a query nested inside another query. The subquery is executed first, and its result is used by the outer query. Subqueries can be used in various places such as:
Let's explore different types of subqueries:
SELECT name, score
FROM students
WHERE score > (SELECT AVG(score) FROM students);SELECT department
FROM employees
GROUP BY department
HAVING AVG(salary) = (
SELECT MAX(avg_salary)
FROM (
SELECT AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
);SELECT product_name, price, category
FROM products p1
WHERE price > (
SELECT AVG(price)
FROM products p2
WHERE p2.category = p1.category
);There are two types of subqueries:
Correlated subqueries are more powerful but can be slower than non-correlated subqueries.
Many queries that use subqueries can also be written using joins. Try rewriting this subquery as a join:
-- Using a subquery
SELECT name
FROM students
WHERE id IN (
SELECT student_id
FROM enrollments
WHERE course_id = 101
);-- Using a join
SELECT DISTINCT students.name
FROM students
INNER JOIN enrollments ON students.id = enrollments.student_id
WHERE enrollments.course_id = 101;In this lesson, we've learned how to use subqueries to create more complex and powerful SQL queries. Subqueries allow you to break down complex problems into smaller, more manageable pieces and can make your queries more readable and maintainable.
You've completed all the SQL lessons! You've learned:
These skills form the foundation of working with databases. Keep practicing and exploring more advanced topics like transactions, indexes, and database normalization!