PostgreSQL Subquery
PostgreSQL Subquery
1 di 5
http://www.postgresqltutorial.com/postgresql-subquery/
PostgreSQL Subquery
Summary: in this tutorial, you will learn how to use the PostgreSQL subquery that allows you to
construct complex queries.
AVG (rental_rate)
3 FROM
4
film
13/12/2016 16.05
PostgreSQL Subquery
2 di 5
http://www.postgresqltutorial.com/postgresql-subquery/
1 SELECT
2
film_id,
title,
rental_rate
5 FROM
6
film
7 WHERE
8
The code is not so elegant, which requires two steps. We want a way to pass the result of the rst
query to the second query in one query. The solution is to use a subquery.
A subquery is a query nested inside another query such as SELECT, INSERT, DELETE and
UPDATE . In this tutorial, we are focusing on the SELECT statement only.
To construct a subquery, we put the second query in brackets and use it in the WHERE clause as an
expression:
1
SELECT
film_id,
title,
rental_rate
FROM
film
WHERE
rental_rate > (
SELECT
10
AVG (rental_rate)
11
FROM
12
film
13
The query inside the brackets is called a subquery or an inner query. The query that contains the
subquery is known as an outer query.
13/12/2016 16.05
PostgreSQL Subquery
3 di 5
http://www.postgresqltutorial.com/postgresql-subquery/
For example, to get lms that have the returned date between 2005-05-29 and 2005-05-30 ,
you use the following query:
1 SELECT
2
inventory.film_id
3 FROM
4
rental
8 AND '2005-05-30'
It returns multiple rows so we can use this query as a subquery in the WHERE clause of a query as
follows:
1
SELECT
film_id,
title
4
5
FROM
film
13/12/2016 16.05
PostgreSQL Subquery
4 di 5
film
WHERE
film_id IN (
SELECT
inventory.film_id
http://www.postgresqltutorial.com/postgresql-subquery/
10
FROM
11
rental
12
13
WHERE
14
15
AND '2005-05-30'
16
A subquery can be an input of the EXISTS operator. If the subquery returns any row, the
EXISTS operator returns true. If the subquery returns no row, the result of EXISTS operator is
false.
The EXISTS operator only cares about the number of rows returned from the subquery, not the
content of the rows, therefore, the common coding convention of EXISTS operator is as follows:
1 EXISTS (SELECT 1 FROM tbl WHERE condition)
SELECT
first_name,
last_name
FROM
13/12/2016 16.05
PostgreSQL Subquery
5 di 5
4
5
6
http://www.postgresqltutorial.com/postgresql-subquery/
FROM
customer
WHERE
EXISTS (
SELECT
10
FROM
11
payment
12
WHERE
13
payment.customer_id = customer.customer_id
14
The query works like an inner join on the customer id column. However, it returns at most one row
for each row in the customer table even though there are some corresponding rows in the
payment table.
In this tutorial, you have learned how to use the PostgreSQL subquery to construct complex
queries.
13/12/2016 16.05