At a high-level, a subquery is a SELECT statement within another SELECT statement. It’s typically involved in a multi-step problem where it’s desirable or necessary to break the problem down into subproblems, solve each individually, and bring the solutions to the subproblems together to solve the overall problem. We may not immediately realize it, but the concept of a subquery and how it works is not entirely new to us. Consider the following expression.5 * (4 + 3) = x
PEMDAS, a well-known acronym standing for PARENTHESIS, EXPONENT, MULTIPLY or DIVIDE, ADD or SUBRACT, tells us to first perform the addition operation located within the parenthesis, and then multiply the intermediate result (i.e., 7) by 5 to solve for x.5 * 7 = x
35 = x
The key takeaway from the example is there is an order of operations and the output or solution to an intermediate problem is used to solve the overall problem. SQL subqueries work in a similar fashion. Understanding subqueries and their use cases is fundamental to learning SQL.
Subqueries can exist in several SQL clauses, including the FROM clause, HAVING clause, WHERE clause, and SELECT clause. Depending on the problem or task, it may be required and/or more appropriate to use a subquery in a specific clause. Explore the use of subqueries within each clause by navigating to the respective page using the links below. Each page will contain real-world examples, allowing you to more easily apply the concepts explored within each page to your current and future problems.
SUBQUERIES IN THE FROM CLAUSE
SUBQUERIES IN THE HAVING CLAUSE
SUBQUERIES IN THE WHERE CLAUSE
SUBQUERIES IN THE SELECT CLAUSE