SQL: Introduction to Subqueries

What is a Subquery?

A subquery is a query made within another larger query. Subqueries can also be called an inner query or a nested query. Since subqueries are nested within a larger query, that larger query is considered an outer query. Another term for subqueries is an inner select and for the outer query, an outer select.

Subquery Syntax

The syntax of a subquery depends on which type of query is being executed and where it’s coded. They can be used in 4 different types of queries: Select, Insert, Update, and Delete. The code can be found within the Select clause, From Clause, or most commonly the Where clause.

SELECT column_1, ..., column_n
FROM Table_1
WHERE expression operator
(SELECT column_1, ..., column_n
FROM Table_2
WHERE condition)

Subquery Example

In our example, there is an online store and we want to know the full names and company, if there is one, of individuals who created orders worth more than $10,000. In an online store, the personal information of the clients and the orders are usually separated into their own tables. So what is our first step?

SELECT client_id
FROM orders
WHERE orders.cost > 10000;
SELECT last_name, first_name, company
FROM clients
WHERE clients.id IN
(SELECT orders.client_id
FROM orders
WHERE orders.cost > 10000);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store