Introduction
CTEs make complex queries easier to read and understand by naming parts of the query clearly instead of nesting subqueries.
WITH cte_name AS ( SELECT column1, column2 FROM table_name WHERE condition ) SELECT * FROM cte_name;
WITH recent_orders AS ( SELECT order_id, customer_id, order_date FROM orders WHERE order_date > '2024-01-01' ) SELECT * FROM recent_orders;
WITH high_value_customers AS ( SELECT customer_id, SUM(amount) AS total_spent FROM sales GROUP BY customer_id HAVING SUM(amount) > 1000 ) SELECT customer_id, total_spent FROM high_value_customers;
WITH top_products AS ( SELECT product_id, SUM(quantity) AS total_sold FROM sales GROUP BY product_id ORDER BY total_sold DESC LIMIT 3 ) SELECT product_id, total_sold FROM top_products;
WITH clause (CTE) instead of a nested subquery in SQL?WITH cte_name AS (subquery), followed by the main query.orders(order_id, customer_id, amount) and customers(customer_id, name), what will this query return?WITH high_orders AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id HAVING SUM(amount) > 100 ) SELECT c.name, h.total FROM high_orders h JOIN customers c ON h.customer_id = c.customer_id;
high_orders groups orders by customer and filters those with total amount > 100.high_orders with customers to get customer names and their total order amounts.WITH recent_orders AS ( SELECT order_id, order_date FROM orders WHERE order_date > '2023-01-01' ) SELECT * FROM recent_orders WHERE order_date < '2023-01-01';
order_date > '2023-01-01'.order_date < '2023-01-01', which contradicts the CTE filter, so no rows match.Pass the test and this pattern moves unknown