PostgreSQL Subquery
Summary: in this tutorial, you will learn how to use the PostgreSQL subquery that allows you to construct complex queries.
Introduction to PostgreSQL subquery
A subquery is a query nested within another query. A subquery is also known as an inner query or nested query.
A subquery can be useful for retrieving data that will be used by the main query as a condition for further data selection.
The basic syntax of the subquery is as follows:
In this syntax, the subquery is enclosed within parentheses and is executed first:
The main query will use the result of the subquery to filter data in the WHERE
clause.
PostgreSQL subquery examples
Let’s take some examples of using subqueries.
1) Basic PostgreSQL subquery example
First, retrieve the country id of the United States
from the country
table:
It returns the following output:
Second, retrieve cities from the city
table where country_id
is 103
:
Output:
Instead of executing two queries, you can combine them into one, making the first query as a subquery and the second query as the main query as follows:
In this query, the following is the subquery:
PostgreSQL executes the subquery first to get the country id and uses it for the WHERE
clause to retrieve the cities.
2) Using a subquery with the IN operator
A subquery can return zero or more rows. If the query returns more than one row, you can use it with the IN operator. For example:
First, retrieve film_id
of the film with the category Action
:
Output:
Second, use the query above as a subquery to retrieve the film title from the film
table:
Output:
Summary
- A subquery is a query nested inside another query
- A subquery is also known as an inner query or nested query.