What is a subquery in PostgreSQL?
Answer
A subquery (inner query or nested query) is a query nested inside another query. It can appear in SELECT, FROM, WHERE, or HAVING clauses. Scalar subquery: returns one value — SELECT name, (SELECT COUNT(*) FROM orders WHERE user_id = u.id) AS order_count FROM users u;. Row subquery: returns one row — WHERE (col1, col2) = (SELECT a, b FROM ...). Table subquery (derived table): in FROM clause — SELECT * FROM (SELECT * FROM users WHERE active = true) AS active_users;. Correlated subquery: references outer query columns — re-executed for each row (often replaced by JOIN or CTE for performance). EXISTS, NOT EXISTS, IN, NOT IN, ANY, ALL operators work with subqueries.
Previous
What is the difference between UNION and UNION ALL?
Next
How do you use COALESCE in PostgreSQL?