MySQL with clause
In this tutorial, we will learn about MySQL WITH
CONSTRUCTED TE clauses, also known as Common Table Expression
(CTE). CTE is used whenever you want to manipulate data with difficult subqueries.
We will also learn Common Table Expression
how CTEs (Complex Type Enumerations) allow you to write complex queries in a way that is easy to read and understand. We will also look at whether we can use nested WITH
clauses.
Please note that this is not available prior to MySQL version 8.0 Common Table Expression
. You must have MySQL 8.0 or higher to use it. You can see what's new in MySQL version 8.0 here.
Use the MySQL WITH
clauseCommon Table Expression
To use MySQL WITH
clauses, let's first understand CTE. Common table expressions (CTE) are named temporary result sets that exist only within the execution scope of the statement in which it is written.
By using WITH
the clause, you can give a complex subquery a name that you can easily use in the main query ( SELECT
, INSERT
, UPDATE
or DELETE
). Keep in mind that not all databases support WITH
the clause.
WITH
You can use one or more subqueries and CTEs in the same IN clause, but not nested WITH
( WITH
another within an IN clause WITH
). Let's create a CTE called tb_order Table
and fill it with some data to exercise WITH
the IN clause.
Sample code:
# SQL Programming Using MySQL Version 8.27
CREATE TABLE `practice_with_clause`.`tb_order` (
ORDER_ID INTEGER NOT NULL,
CUSTOMER_FIRST_NAME VARCHAR(30) NOT NULL,
CUSTOMER_LAST_NAME VARCHAR(30) NOT NULL,
CITY_NAME VARCHAR(64) NOT NULL,
PURCHASED_PRODUCTS VARCHAR(64) NOT NULL,
ORDER_DATE DATE NOT NULL,
PRIMARY KEY (ORDER_ID)
);
Make sure your table was created successfully in Tables
under .Database
Use the following INSERT
command to populate the table with 7 records.
# SQL Programming Using MySQL Version 8.27
INSERT INTO practice_with_clause.tb_order
(ORDER_ID, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CITY_NAME, PURCHASED_PRODUCTS, ORDER_DATE)
VALUES
(1,'John','Horton', 'Washington', 'Books', '2021-05-03'),
(2,'Banji','Horton', 'Florida', 'Pens', '2010-5-6'),
(3,'Nayya','Sofia', 'South Carolina', 'Books', '2011-10-15'),
(4,'Martell','Daniel', 'Michigan', 'NoteBooks', '2012-12-02'),
(5,'Sana','Preston', 'Michigan', 'White Board Marker', '2013-08-27'),
(6,'Gulraiz','Yonja', 'Washington', 'Books', '2021-05-03'),
(7,'Mashal','Naaz', 'Florida', 'Comic Books', '2019-01-01');
Now, use SELECT
the command to view the data.
# SQL Programming Using MySQL Version 8.27
SELECT * FROM practice_with_clause.tb_order;
At this point, we will use WITH
the clause to use common table expressions and operate complex subqueries as shown below.
# SQL Programming Using MySQL Version 8.27
WITH cte_order AS
(
SELECT PURCHASED_PRODUCTS, COUNT(ORDER_ID) as Number_of_Orders
FROM practice_with_clause.tb_order
GROUP BY PURCHASED_PRODUCTS
)
SELECT AVG(Number_of_Orders) AS "Average Orders Per Category"
FROM cte_order;
Let's break the above query into its parts to understand it:
Common table expressions:cte_order
Subquery:
SELECT PURCHASED_PRODUCTS, COUNT(ORDER_ID) as Number_of_Orders FROM practice_with_clause.tb_order GROUP BY PURCHASED_PRODUCTS
Main query:
SELECT AVG(Number_of_Orders) AS "Average Orders Per Category" FROM cte_order;
Note that the CTE references itself in the main query to read the data. It will display the following output based on my data (your output may be different).
公用表表达式
Scope of Implementation
As we said, CTE works only within the scope of its execution, how? See the following screenshot.
When you select only the code highlighted by the green box, you are still cte_order
within the execution scope of the CTE named , but when you select only the code within the red box, you are now outside the execution scope and cannot reference the common table expression named . This means that you can reference the CTE in cte_order
the same clause in which you wrote it .WITH
Using 公共表表达式
MySQL with multiple WITH
clauses
Let's practice using multiple common table expressions WITH
.
WITH
cte_order AS
(
SELECT PURCHASED_PRODUCTS, COUNT(ORDER_ID) as Number_of_Orders
FROM practice_with_clause.tb_order
GROUP BY PURCHASED_PRODUCTS
),
cte_location AS
(
SELECT COUNT(CITY_NAME) as City
FROM practice_with_clause.tb_order
WHERE CITY_NAME = 'Washington'
)
SELECT AVG(Number_of_Orders) AS "Average Orders Per Category", City
FROM cte_order,cte_location;
You will now see the following output.
Similarly, we can also reference a Common Table Expression defined previously from another CTE. Make sure both common table expressions are written in the same WITH
clause.
in conclusion
Considering the above discussion, we conclude that WITH
the clause is used to obtain 公共表表达式
advantages that help in manipulating difficult subqueries. We can WITH
use multiple subqueries and common table expressions in the same INSERT clause, but we cannot have nested INSERT WITH
clauses. We also cannot reference CTEs from different WITH
INSERT clauses.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Changing max_allowed_packet Size in MySQL Server
Publish Date:2025/04/22 Views:192 Category:MySQL
-
This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi
Zerofill usage, advantages and alternatives in MySQL
Publish Date:2025/04/22 Views:195 Category:MySQL
-
In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input
Compare only MySQL timestamp dates to date parameters
Publish Date:2025/04/22 Views:64 Category:MySQL
-
In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi
Calculating Percentages in MySQL
Publish Date:2025/04/22 Views:66 Category:MySQL
-
We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re
Selecting multiple values using WHERE in MySQL
Publish Date:2025/04/22 Views:185 Category:MySQL
-
This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi
Changing the connection timeout in MySQL
Publish Date:2025/04/22 Views:59 Category:MySQL
-
We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti
MySQL fix Data Is Truncated for a Column error
Publish Date:2025/04/22 Views:101 Category:MySQL
-
This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca
MySQL Error Server PID File Could Not Be Found Solution
Publish Date:2025/04/22 Views:192 Category:MySQL
-
In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My
Get the last inserted ID using PHP MySQLi function
Publish Date:2025/04/22 Views:99 Category:MySQL
-
This article briefly introduces the PHP mysqli() function and demonstrates how to use it to get the last inserted ID from a MySQL database. PHP mysqli() Function It is an extended version of the MySQL driver called mysqli and is typically u