Junior — Middle
Explain the purpose and use of the WITH operator in SQL queries.
sobes.tech AI
Answer from AI
The WITH operator in SQL 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, helps avoid code duplication, and simplifies maintenance.
Example of usage:
WITH RecentOrders AS (
SELECT * FROM orders WHERE order_date > '2024-01-01'
)
SELECT customer_id, COUNT(*)
FROM RecentOrders
GROUP BY customer_id;
Here, a temporary dataset RecentOrders is created first, which is then used in the main SELECT query. This is especially useful when building multi-step or recursive queries.