![]() |
One of the most powerful features added in MySQL version 8.0 is common table expressions, which allow for the construction of temporary result sets within a single SQL query. In our daily life queries, we often use common table expressions and it makes our work easier. In this article, we will understand the Common Table Expression with examples and also we will learn how to use the statements. What is a Common Table ExpressionA common table expression is a temporary result set that’s named and which you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. Temporary result sets are usually referred to in the execution of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. CTEs are absolutely necessary to reduce complex queries down to standard readable and reusable pieces of code. Moreover, CTEs might be recursive—thereby permitting extremely complicated hierarchical or recursive queries. Syntax of CTEsThe basic syntax of a CTE in MySQL is as follows: WITH cte_name (column1, column2, ...) AS ( where,
Examples of MySQL Common Table ExpressionsHere are some examples of MySQL Common Table Expressions: Simplifying a Complex QuerySuppose that you have the table employees and you need to compute the total and average salary by department; then, among those, find the departments above an average salary of $60,000. Create TableCREATE TABLE employees ( Insert Data into TableINSERT INTO employees (name, department, salary) VALUES CTE QueryWITH department_salaries AS ( Output:
Explanation: The above example uses a Common Table Expression to determine the total and average salary by department from some Employees table. Here, the following CTE is named department_salaries. It aggregates the total and average salaries for each department. The main query then selects departments where the average salary exceeds $60,000. By using the CTE, the query becomes more readable and maintainable by breaking down this complex aggregation and filtering into clear, logical steps. Recursive CTE for Hierarchical DataSuppose these table categories represent a hierarchical category structure with a self-referencing foreign key parent_id. Create TableCREATE TABLE categories ( Insert Data Into TableINSERT INTO categories (name, parent_id) VALUES CTE Query to List All SubcategoriesWITH RECURSIVE category_hierarchy AS ( Output:
Explanation: This example shows the listing of all categories and their subcategories in a “categories table” where there is a self-referencing column for parent_id. Here, it uses a recursive Common Table Expression named category_hierarchy that starts off with the selection of top-level categories where parent_id is NULL, then recursively joins to include subcategories, incrementing a level column to show depth in hierarchy. Temporary AggregationLet there be a table sales and you need to calculate the total sales for each salesperson, then filter those that achieved sales more than a given cutoff value. Create TableCREATE TABLE sales ( Insert Data Into TablesINSERT INTO sales (salesperson_id, sales_amount) VALUES CTE QueryWITH total_sales AS ( Output:
Explanation: The example shows the use of Common Table Expressions in computing aggregate data and then reusing this aggregate inside a single query. Here, it creates a CTE called total_sales that computes the total amount of sales for each salesperson by grouping data from the sales table. It then selects from this total_sales CTE those salespersons with total sales greater than $5000. Benefits of Using CTEsHere are some benefits of the CTE:
ConclusionMySQL Common Table Expressions are used often by us in SQL queries. Whether it is creating a table or resolving any query you will need them. By the above article, you can understand Common Table Expressions easily with the help of the examples. MySQL Common Table Expressions – FAQsWhat are common table expressions in MySQL?
What are expressions in MySQL?
How to write 2 CTE in MySQL?
|
Reffered: https://www.geeksforgeeks.org
Databases |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 22 |