JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

MySQL with clause

Author:JIYIK Last Updated:2025/04/22 Views:

In this tutorial, we will learn about MySQL WITHCONSTRUCTED 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 Expressionhow 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 WITHclauses.

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 WITHclauseCommon Table Expression

To use MySQL WITHclauses, 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 WITHthe clause, you can give a complex subquery a name that you can easily use in the main query ( SELECT, INSERT, UPDATEor DELETE). Keep in mind that not all databases support WITHthe clause.

WITHYou can use one or more subqueries and CTEs in the same IN clause, but not nested WITH( WITHanother within an IN clause WITH). Let's create a CTE called tb_order Tableand fill it with some data to exercise WITHthe 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 Tablesunder .Database

Use the following INSERTcommand 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 SELECTthe 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 WITHthe 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_orderwithin 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_orderthe same clause in which you wrote it .WITH


Using 公共表表达式MySQL with multiple WITHclauses

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 WITHclause.


in conclusion

Considering the above discussion, we conclude that WITHthe clause is used to obtain 公共表表达式advantages that help in manipulating difficult subqueries. We can WITHuse multiple subqueries and common table expressions in the same INSERT clause, but we cannot have nested INSERT WITHclauses. We also cannot reference CTEs from different WITHINSERT 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.

Article URL:

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial