Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Introduction to CTEs: Syntax and Benefits | CTE Fundamentals and Syntax
Mastering Common Table Expressions (CTEs) in SQL

bookIntroduction to CTEs: Syntax and Benefits

Свайпніть щоб показати меню

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.

1234567
WITH HighEarners AS ( SELECT employee_id, first_name, last_name, salary FROM employees WHERE salary > 55000 ) SELECT * FROM HighEarners;
copy

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;
copy

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?

question mark

What is the main advantage of using a CTE over a subquery?

Select the correct answer

question mark

Which SQL keyword is used to define a CTE?

Select the correct answer

question mark

Can a CTE be referenced multiple times within the same query?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 1
some-alt