Bird
Raised Fist0
SQLquery~20 mins

Why CTEs are needed in SQL - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CTE Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use Common Table Expressions (CTEs)?

Which of the following best explains why CTEs are useful in SQL queries?

ACTEs store data permanently in the database for faster access.
BCTEs allow breaking complex queries into simpler parts for better readability and reuse.
CCTEs replace the need for any JOIN operations in SQL queries.
DCTEs automatically speed up query execution by creating indexes on the fly.
Attempts:
2 left
💡 Hint

Think about how CTEs help organize and structure queries.

❓ query_result
intermediate
2:30remaining
Output of a query using a CTE

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;
SQL
Employees:
1, 'Alice', 10
2, 'Bob', 20
3, 'Charlie', 10
4, 'Diana', 30
5, 'Eve', 20

Departments:
10, 'HR'
20, 'Sales'
30, 'IT'
A[('IT', 1), ('HR', 2), ('Sales', 2)]
B[('HR', 2), ('Sales', 2), ('IT', 1)]
C[('Sales', 2), ('HR', 2), ('IT', 1)]
D[('HR', 3), ('Sales', 2), ('IT', 1)]
Attempts:
2 left
💡 Hint

Count employees per department, then join with department names and order by count descending.

📝 Syntax
advanced
1:30remaining
Identify the syntax error in this CTE query

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;
ANo syntax error; the query is valid.
BMissing comma after CTE definition before SELECT statement.
CCTE must be followed by a semicolon before the main SELECT.
DIncorrect use of WHERE clause inside the CTE.
Attempts:
2 left
💡 Hint

Check if the CTE and main query are properly connected.

❓ optimization
advanced
2:00remaining
Why might using a CTE hurt performance?

Which reason explains why CTEs can sometimes reduce query performance?

ACTEs are always materialized, causing repeated computation if referenced multiple times.
BCTEs automatically create indexes that slow down queries.
CCTEs force the database to scan all tables even if not needed.
DCTEs prevent the use of any WHERE clauses in the main query.
Attempts:
2 left
💡 Hint

Think about how databases handle CTEs internally.

🔧 Debug
expert
3:00remaining
Why does this recursive CTE cause an infinite loop?

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?

AThe UNION ALL should be UNION to avoid duplicates.
BRecursive CTEs are not supported in standard SQL.
CThe initial SELECT does not specify a column alias.
DThe recursive part lacks a proper termination condition causing infinite recursion.
Attempts:
2 left
💡 Hint

Check the condition that stops recursion.

Practice

(1/5)
1. Why do we use Common Table Expressions (CTEs) in SQL queries?
easy
A. To speed up the database server hardware
B. To break complex queries into simpler, readable parts
C. To store data permanently like tables
D. To create indexes automatically

Solution

  1. Step 1: Understand the purpose of CTEs

    CTEs help organize complex SQL queries by dividing them into smaller, manageable parts.
  2. Step 2: Compare other options

    Options B, C, and D describe unrelated database functions like hardware speed, permanent storage, and indexing, which are not the purpose of CTEs.
  3. Final Answer:

    To break complex queries into simpler, readable parts -> Option B
  4. Quick Check:

    CTEs simplify queries = A [OK]
Hint: CTEs make big queries easier to read and manage [OK]
Common Mistakes:
  • Thinking CTEs improve hardware speed
  • Confusing CTEs with permanent tables
  • Assuming CTEs create indexes automatically
2. Which of the following is the correct syntax to start a CTE in SQL?
easy
A. WITH cte_name AS (SELECT * FROM table_name)
B. CREATE CTE cte_name SELECT * FROM table_name
C. DEFINE cte_name AS SELECT * FROM table_name
D. START CTE cte_name (SELECT * FROM table_name)

Solution

  1. Step 1: Recall standard CTE syntax

    The correct way to define a CTE is using the WITH keyword followed by the CTE name and AS, then the query in parentheses.
  2. Step 2: Check other options for syntax errors

    Options A, C, and D use incorrect keywords like CREATE, DEFINE, or START which are not valid for CTEs.
  3. Final Answer:

    WITH cte_name AS (SELECT * FROM table_name) -> Option A
  4. Quick Check:

    CTE starts with WITH ... AS (...) = B [OK]
Hint: CTEs always start with WITH keyword [OK]
Common Mistakes:
  • Using CREATE instead of WITH
  • Omitting AS keyword
  • Not enclosing query in parentheses
3. Given the query:
WITH SalesCTE AS (SELECT salesperson, SUM(amount) AS total_sales FROM sales GROUP BY salesperson) SELECT * FROM SalesCTE WHERE total_sales > 1000;
What does this query return?
medium
A. Error because CTE cannot be filtered
B. All sales records with amount greater than 1000
C. Sum of all sales amounts in the sales table
D. Salespersons with total sales greater than 1000

Solution

  1. Step 1: Analyze the CTE definition

    The CTE named SalesCTE groups sales by salesperson and calculates total sales per person.
  2. Step 2: Understand the main query filter

    The main query selects only those salespersons whose total sales exceed 1000.
  3. Final Answer:

    Salespersons with total sales greater than 1000 -> Option D
  4. Quick Check:

    CTE groups and filters salespersons by total sales > 1000 = A [OK]
Hint: CTEs can be filtered in main query like tables [OK]
Common Mistakes:
  • Thinking it returns individual sales over 1000
  • Assuming it sums all sales without grouping
  • Believing CTEs cannot be filtered
4. Identify the error in this SQL query using a CTE:
WITH cte AS SELECT id, name FROM users SELECT * FROM cte;
medium
A. Missing parentheses around the CTE query
B. CTE name cannot be 'cte'
C. SELECT * FROM cte should come before WITH clause
D. No error, query is correct

Solution

  1. Step 1: Check CTE syntax

    The CTE query must be enclosed in parentheses after AS keyword.
  2. Step 2: Verify query order and naming

    The CTE name 'cte' is valid, and the main SELECT comes after the CTE definition, so no error there.
  3. Final Answer:

    Missing parentheses around the CTE query -> Option A
  4. Quick Check:

    CTE query must be in parentheses = D [OK]
Hint: Always put CTE query inside parentheses after AS [OK]
Common Mistakes:
  • Omitting parentheses around CTE query
  • Placing main SELECT before WITH clause
  • Thinking CTE names are restricted
5. You want to find all employees who manage themselves directly or indirectly in a company hierarchy stored in a table employees(id, name, manager_id). Why is a recursive CTE needed here?
hard
A. Because recursive CTEs store data permanently for future use
B. Because recursive CTEs automatically create indexes for faster queries
C. Because recursive CTEs can repeatedly join the table to find all levels of management
D. Because recursive CTEs replace the need for GROUP BY clauses

Solution

  1. Step 1: Understand the problem of hierarchical queries

    Finding all managers up the chain requires repeatedly joining the table to itself for multiple levels.
  2. Step 2: Recognize recursive CTE capability

    Recursive CTEs allow a query to call itself to traverse hierarchical data until all levels are found.
  3. Final Answer:

    Because recursive CTEs can repeatedly join the table to find all levels of management -> Option C
  4. Quick Check:

    Recursive CTEs handle hierarchical recursion = C [OK]
Hint: Use recursive CTEs for multi-level hierarchical queries [OK]
Common Mistakes:
  • Thinking recursive CTEs create indexes
  • Confusing recursive CTEs with permanent storage
  • Assuming recursive CTEs replace GROUP BY
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard