</>
Skip to content
PostgreSQL lessons (20/38)

PostgreSQL — Subqueries

Basic Subquery

SELECT * FROM users 
WHERE id IN (SELECT user_id FROM orders WHERE total > 100);

Subquery in FROM

SELECT avg_total 
FROM (SELECT AVG(total) as avg_total FROM orders) subquery;

Subquery in SELECT

SELECT name, 
    (SELECT COUNT(*) FROM orders WHERE user_id = users.id) as order_count
FROM users;

Correlated Subquery

SELECT * FROM users u
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);

ANY / ALL

-- Greater than any
SELECT * FROM products WHERE price > ANY (SELECT price FROM products WHERE category = 'food');

-- Greater than all
SELECT * FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'food');

Subquery Types

TypeDescription
ScalarReturns single value
RowReturns single row
TableReturns table
CorrelatedReferences outer query

Mini Practice

  1. Use subquery in WHERE
  2. Use subquery in FROM
  3. Use correlated subquery
  4. Use ANY and ALL

Up Next

Continue with CTE — common table expressions.

Related Topics

Frequently Asked Questions about Subqueries

What is Subqueries in PostgreSQL?

Subqueries is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Subqueries?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Subqueries.

Why is Subqueries important in PostgreSQL?

Subqueries is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.