Introduction to CTEs: Syntax and Benefits
Veeg om het menu te tonen
Common Table Expressions, or CTEs, are a powerful feature in SQL that allow you to define a temporary, named result set within the execution scope of a single query. You use CTEs to organize complex queries, break them into logical building blocks, and improve both readability and maintainability. CTEs are especially useful when you need to reference a derived table multiple times in a query, or when you want to simplify deeply nested subqueries. Whenever you find yourself struggling to follow a long query with multiple subqueries, or you need to reuse a calculated result, a CTE can make your SQL much clearer and easier to manage.
1234567WITH HighEarners AS ( SELECT employee_id, first_name, last_name, salary FROM employees WHERE salary > 55000 ) SELECT * FROM HighEarners;
Let's break down the syntax of a CTE step by step. You start with the WITH clause, which signals the beginning of one or more CTE definitions. Next, you provide a CTE name, such as HighEarners, followed by the CTE's query enclosed in parentheses. This query defines the temporary result set. After the CTE is defined, you write your main query, which can reference the CTE just like a regular table. In the example above, the main query simply selects all columns from HighEarners. By naming the CTE, you make your query's intent clear and allow for easy reuse of the derived result.
123456789101112131415161718-- Using a subquery SELECT employee_id, first_name, last_name FROM ( SELECT employee_id, first_name, last_name, salary FROM employees WHERE department_id = 1 ) AS SalesEmployees WHERE salary > 55000; -- Using a CTE for clarity WITH SalesEmployees AS ( SELECT employee_id, first_name, last_name, salary FROM employees WHERE department_id = 1 ) SELECT employee_id, first_name, last_name FROM SalesEmployees WHERE salary > 55000;
1. What is the main advantage of using a CTE over a subquery?
2. Which SQL keyword is used to define a CTE?
3. Can a CTE be referenced multiple times within the same query?
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.