Junior — Middle
Explain how the WITH construct functions in PostgreSQL and what role it plays in query organization.
sobes.tech AI
Answer from AI
The WITH clause in PostgreSQL is used to define temporary named subqueries (Common Table Expressions, CTEs) that can be used within the main query. This improves readability and structure of complex queries, allowing them to be broken down into logical parts.
Example of usage:
WITH recent_orders AS (
SELECT * FROM orders WHERE order_date > CURRENT_DATE - INTERVAL '7 days'
)
SELECT customer_id, COUNT(*) FROM recent_orders GROUP BY customer_id;
Here, the CTE recent_orders is defined first, which selects orders from the last 7 days, and then the main query aggregates data by customers.
CTEs can also be recursive, which is useful for working with hierarchical data.
Thus, WITH helps organize queries more clearly and modularly, improving code maintenance and readability.