CTE in MySQL for Java Developer

Rajat Rastogi
4 min readAug 26, 2023

--

Introduction to Common Table Expression (CTE) in MySQL?

A Common Table Expression (CTE) is a temporary named result set that is defined within the scope of a single SQL query. It allows you to write complex queries in a more readable and maintainable manner, by breaking them down into smaller, logical steps. CTEs can be used in MySQL with the “WITH” keyword, followed by the name of the CTE and the SELECT statement that defines it. Once a CTE is defined, it can be referenced multiple times within the same query.

One of the main benefits of using CTEs is that they allow you to create recursive queries, which are queries that reference themselves. This can be useful for tasks such as generating hierarchical data or finding the shortest path between nodes in a graph. CTEs can also be used to simplify the syntax of complex joins, to create derived tables that can be used within other queries, or to improve query performance by reducing the number of times that a subquery needs to be executed.

MySQL CTE Syntax

The basic syntax for creating a Common Table Expression (CTE) in MySQL is as follows:

WITH cte_name AS (
SELECT column1, column2, ...
FROM table_name
WHERE condition
)
SELECT *
FROM cte_name;

It is also possible to define multiple CTEs within the same query, by separating each CTE definition with a comma. For example:

WITH cte1 AS (
SELECT column1, column2, ...
FROM table1
WHERE condition1
),
cte2 AS (
SELECT column3, column4, ...
FROM table2
WHERE condition2
)
SELECT *
FROM cte1
JOIN cte2 ON cte1.column1 = cte2.column3;

In this example, two CTEs are defined: “cte1” and “cte2”. The CTEs are then referenced in the main query by joining them on a common column and selecting all columns from both CTEs.

MySQL Recursive CTE Syntax

MySQL Recursive Common Table Expressions (CTEs) is a powerful feature that allows you to define a CTE that refers to itself. Recursive CTEs can be used to traverse hierarchical data structures, such as trees or graphs, and perform operations on each level of the hierarchy.

The syntax for creating a recursive CTE in MySQL is similar to that of a regular CTE, with the addition of a UNION ALL operator that allows the CTE to refer to itself. Here is an example of a simple recursive CTE in MySQL:

WITH RECURSIVE cte_name AS (
SELECT id, parent_id, name
FROM table_name
WHERE parent_id IS NULL
UNION ALL
SELECT child.id, child.parent_id, child.name
FROM table_name child
JOIN cte_name parent ON child.parent_id = parent.id
)
SELECT *
FROM cte_name;

MySQL CTE Examples

An example of how Common Table Expressions (CTEs) can be used in MySQL:

Suppose you have a sales table with columns “product_name”, “sales_date”, and “revenue”. You want to calculate the total revenue for each product over the past 30 days, as well as the percentage change in revenue compared to the previous 30-day period. You can use a CTE to calculate these metrics:

CREATE TABLE sales (
product_name VARCHAR(50),
sales_date DATE,
revenue DECIMAL(10, 2)
);
INSERT INTO sales (product_name, sales_date, revenue) VALUES 
('Product A', '2023-03-01', 1000),
('Product A', '2023-03-15', 1500),
('Product A', '2023-03-30', 2000),
('Product B', '2023-03-01', 800),
('Product B', '2023-03-15', 1200),
('Product B', '2023-03-30', 1600),
('Product C', '2023-03-01', 500),
('Product C', '2023-03-15', 750),
('Product C', '2023-03-30', 1000);

The Image depicts the table data of the following table sales.

Query -

WITH sales_last_30_days AS (
SELECT product_name, SUM(revenue) AS total_revenue
FROM sales
WHERE sales_date BETWEEN '2023-03-10' AND '2023-04-09'
GROUP BY product_name
),
sales_previous_30_days AS (
SELECT product_name, SUM(revenue) AS total_revenue
FROM sales
WHERE sales_date BETWEEN '2023-02-08' AND '2023-03-09'
GROUP BY product_name
)
SELECT
s.product_name,
s.total_revenue,
(s.total_revenue - p.total_revenue) / p.total_revenue * 100 AS revenue_change
FROM sales_last_30_days s
JOIN sales_previous_30_days p ON s.product_name = p.product_name;

Output -

Benefits of Using CTE

Here are some of the benefits of using Common Table Expressions (CTEs) in MySQL:

  • Simplify complex queries:
    CTEs can be used to break down complex queries into smaller, more manageable parts. By defining CTEs, you can avoid writing complex subqueries multiple times, which can make your code easier to read and understand.
  • Improve query performance:
    CTEs can help improve query performance by reducing the number of database scans required to execute a query. By defining a CTE, you can create a temporary table that can be used to store intermediate results, which can reduce the number of scans required to retrieve data.
  • Reuse code:
    CTEs can be used to create modular SQL code that can be reused across multiple queries. By defining a CTE at the beginning of a query, you can create a self-contained module that can be used in other queries, making your code more flexible and adaptable.
  • Traverse hierarchical data:
    CTEs can be used to traverse hierarchical data structures, such as organizational charts or product categories. By defining a recursive CTE, you can traverse the hierarchy and perform complex calculations on the data.

--

--