A CTE is useful when you want to write a query once and reuse its result multiple times within the same query, improving readability and maintainability.
Employees with columns id, name, and department, what is the output of the following queries?Query 1 (using subquery):
SELECT name FROM Employees WHERE department = (SELECT department FROM Employees WHERE id = 3);
Query 2 (using view):
CREATE VIEW DeptView AS SELECT department FROM Employees WHERE id = 3;
SELECT name FROM Employees WHERE department = (SELECT department FROM DeptView);
Assuming employee with
id=3 belongs to 'Sales' department, what will both queries return?Both queries filter employees by the department of employee with id=3, which is 'Sales'. Both return all employees in 'Sales'. Views can be used in subqueries.
WITH SalesCTE AS (SELECT * FROM Sales WHERE amount > 1000) SELECT * FROM SalesCTE;
Option B is the correct syntax for a CTE: WITH name AS (query) SELECT .... Other options miss AS, parentheses, or have misplaced semicolons.
Views and CTEs are query definitions, not physical tables. Performance depends on how the database optimizes the query and indexes available.
CREATE VIEW RecentOrders AS SELECT * FROM Orders WHERE order_date > '2024-01-01';
SELECT customer_id, COUNT(*) FROM RecentOrders GROUP BY customer_id HAVING COUNT(*) > 5;
Why might this query fail in some SQL systems?
Some SQL systems require the view to be referenced with schema name (e.g., dbo.RecentOrders). Without it, the query may fail due to object not found.
