SQL Subquery Examples
A subquery allows you to treat the results of a query like a temporary table.
-- Works in PostgreSQL, MySQL, SQL Server, and Oracle
SELECT
*
FROM (
SELECT
id,
payment_date,
dollar_amount
FROM
rent_payments
WHERE
dollar_amount >= 1800;
) expensive_rent_payments;
rent_payments
table
id | tenant_id | payment_date | dollar_amount |
---|---|---|---|
1 | 1 | 3/1/2018 | 2000 |
2 | 2 | 3/2/2018 | 1500 |
3 | 3 | 3/1/2018 | 1800 |
4 | 4 | 3/3/2018 | 1900 |
5 | 1 | 4/2/2018 | 2000 |
6 | 2 | 4/2/2018 | 1500 |
7 | 3 | 4/1/2018 | 1800 |
8 | 4 | 4/2/2018 | 1900 |
Query results
id | payment_date | dollar_amount |
---|---|---|
1 | 3/1/2018 | 2000 |
3 | 3/1/2018 | 1800 |
4 | 3/3/2018 | 1900 |
5 | 4/2/2018 | 2000 |
7 | 4/1/2018 | 1800 |
8 | 4/2/2018 | 1900 |