Which of the following best explains why CTEs are useful in SQL queries?
Think about how CTEs help organize and structure queries.
CTEs let you write a temporary named result set that you can reference multiple times in a query. This makes complex queries easier to read and maintain. They do not create indexes or store data permanently.
Given the following tables:
Employees: (id, name, department_id)
Departments: (id, name)
What is the output of this query?
WITH DeptCount AS ( SELECT department_id, COUNT(*) AS emp_count FROM Employees GROUP BY department_id ) SELECT d.name, dc.emp_count FROM Departments d JOIN DeptCount dc ON d.id = dc.department_id ORDER BY dc.emp_count DESC;
Employees: 1, 'Alice', 10 2, 'Bob', 20 3, 'Charlie', 10 4, 'Diana', 30 5, 'Eve', 20 Departments: 10, 'HR' 20, 'Sales' 30, 'IT'
Count employees per department, then join with department names and order by count descending.
The CTE counts employees per department. Joining with Departments gives names. Ordering by count descending shows Sales and HR both have 2 employees, Sales listed first alphabetically.
Which option contains the syntax error in the CTE usage?
WITH RecentOrders AS ( SELECT order_id, customer_id, order_date FROM Orders WHERE order_date > '2024-01-01' ) SELECT * FROM RecentOrders WHERE customer_id = 123;
Check if the CTE and main query are properly connected.
The query correctly defines a CTE and then selects from it. The WHERE clause inside the CTE is valid. No comma or semicolon is required between CTE and main query.
Which reason explains why CTEs can sometimes reduce query performance?
Think about how databases handle CTEs internally.
Some databases materialize CTEs, meaning they compute and store the result temporarily. This forces full computation of the CTE upfront, which can prevent optimizations like predicate pushdown and lead to slower performance.
Consider this recursive CTE to generate numbers:
WITH RECURSIVE Numbers AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM Numbers WHERE num < 5 ) SELECT * FROM Numbers;
Why might this query run indefinitely in some databases?
Check the condition that stops recursion.
The recursive CTE appears to have a termination condition (num < 5), but because it is applied to the growing Numbers table which always retains the initial rows (< 5), the recursive SELECT keeps producing rows (num + 1 from those early rows), causing infinite recursion unless limited by database max depth.