Challenge - 5 Problems
CTE vs Subquery vs View Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
When to use a CTE instead of a subquery?
Which situation best justifies using a Common Table Expression (CTE) instead of a subquery in SQL?
Attempts:
2 left
💡 Hint
Think about readability and reusability inside a single query.
✗ Incorrect
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.
❓ query_result
intermediate2:00remaining
Output difference between subquery and view
Given a table
Query 1 (using subquery):
Query 2 (using view):
Assuming employee with
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?Attempts:
2 left
💡 Hint
Think about how subqueries and views work in filtering data.
✗ Incorrect
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.
📝 Syntax
advanced2:00remaining
Identify the correct syntax for CTE usage
Which of the following SQL statements has correct syntax when defining a CTE?
SQL
WITH SalesCTE AS (SELECT * FROM Sales WHERE amount > 1000) SELECT * FROM SalesCTE;
Attempts:
2 left
💡 Hint
Check the placement of AS and parentheses in CTE syntax.
✗ Incorrect
Option B is the correct syntax for a CTE: WITH name AS (query) SELECT .... Other options miss AS, parentheses, or have misplaced semicolons.
❓ optimization
advanced2:00remaining
Performance impact of views vs CTEs
Which statement about performance is true when comparing views and CTEs in SQL?
Attempts:
2 left
💡 Hint
Think about how views and CTEs are processed by the database engine.
✗ Incorrect
Views and CTEs are query definitions, not physical tables. Performance depends on how the database optimizes the query and indexes available.
🔧 Debug
expert2:00remaining
Why does this query with a view fail?
Consider this SQL code:
Why might this query fail in some SQL systems?
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?
Attempts:
2 left
💡 Hint
Consider database-specific requirements for referencing views.
✗ Incorrect
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.