In this PostgreSQL post explains how to use subqueries in PostgreSQL with syntax and examples.
In PostgreSQL, a subquery is a query within a query. You can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
For example:
The subquery portion of the SELECT statement above is:
This subquery allows you to find all category_id values from the categories table that have a category_id greater than 25 and the category_name starts with 'S'. The subquery is then used to filter the results from the main query using the IN condition.
This subquery could have alternatively been written as an INNER join as follows:
This INNER JOIN would run more efficiently than the original subquery. It is important to note, though, that not all subqueries can be rewritten using joins.
A subquery can also be found in the FROM clause. These are called inline views.
For example:
In this example, we've created a subquery in the FROM clause as follows:
This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields.
A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the sum, count, min, max , or avg function, but you do not want the aggregate function to apply to the main query.
For example:
In this example, we've created a subquery in the SELECT clause as follows:
The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields.
The trick to placing a subquery in the SELECT clause is that the subquery must return a single value. This is why an aggregate function such as the sum, count, min, max, or avg function is commonly used in the subquery.