A subquery is a SELECT statement nested inside another SQL command, allowing multi-step filtering, aggregation, and data transformation in ParadeDB.
Subqueries let you break complex logic into smaller steps: filter parent queries, build on intermediate aggregates, or feed derived tables to JOINs without creating temporary tables.
ParadeDB (built on PostgreSQL) accepts subqueries in SELECT, FROM, WHERE, HAVING, INSERT, UPDATE, and DELETE clauses, giving you flexible, composable SQL.
Wrap a SELECT that returns one row and one column in parentheses.It acts like a single value in the outer query.
SELECT id,
(SELECT COUNT(*)
FROM OrderItems oi WHERE oi.order_id = o.id) AS item_count
FROM Orders o;
Use FROM-level subqueries—also called derived tables—when you need to JOIN or re-filter an intermediate result set.Give it an alias right after the closing parenthesis.
SELECT c.name, recent_orders.total
FROM (
SELECT customer_id, SUM(total_amount) AS total
FROM Orders
WHERE order_date > CURRENT_DATE - INTERVAL '30 days'
GROUP BY customer_id
) recent_orders
JOIN Customers c ON c.id = recent_orders.customer_id;
A correlated subquery references columns from the outer query, executing once per outer row.They excel at row-wise checks like existence tests.
SELECT name
FROM Products p
WHERE EXISTS (
SELECT 1 FROM OrderItems oi
WHERE oi.product_id = p.id);
Add indexes on join and filter columns, prefer EXISTS/NOT EXISTS over IN/NOT IN for large sets, and move heavy work to common table expressions (CTEs) when readability matters.
CTEs improve readability and can be referenced multiple times, but they materialize in older PostgreSQL versions.For one-off, simple nesting, subqueries are faster.
.
Yes, ParadeDB follows PostgreSQL rules and supports arbitrarily deep nesting, but readability and performance can degrade. Limit nesting to two levels and refactor with CTEs when queries grow complex.
Yes, unless they are uncorrelated and can be folded as constants. Use JOINs or move heavy logic to CTEs if you see performance issues.
Not always. Until PostgreSQL 12, CTEs were optimization fences. Modern versions inline simple CTEs, aligning their speed with subqueries. Benchmark both approaches for critical queries.