Introduction to the MySQL Common Table Expression - Simple Talk (2023)

This article is part of Robert Sheldon's ongoing series on learning MySQL. To view all 11 articles in the series,Click here.

As with many relational database management systems, MySQL provides a variety of methods for combining data in a DML (data manipulation language) statement. You can join multiple tables in a single query, or add subqueries that retrieve data from other tables. You can also access temporary tables and views from one statement, often with permanent tables.

MySQL also provides another valuable tool for working with data: the Common Table Expression (CTE). A CTE is a named result set that is defined in aCONClause. theCONThe clause is associated with a single DML declaration, but it is built outside of the declaration. However, only this statement can access the result set.

In some cases, it may include a CTESELECTStatement embedded within another statement, such as a subquery or aDELETE... SELECTExpression. But even then, theCONThe clause is defined outside of it.SELECTstatement, and only thatSELECTstatement can access the result set.

One way to think of a CTE is as a view type with a very limited scope (a declaration). Another way to think of a CTE is as a kind of named subquery, defined in a separate clause from the main query. However, a CTE is neither and in this article I will explain how the CTE works and walk you through a series of examples showing the different ways you can use it to retrieve data.

Note: The examples use the tables and data created in the last section of the article titled "Appendix: Preparing the demo objects and data."

Introduction to common table expressions

A common table expression is defined within aCONClause. The clause comes before the main DML declaration, sometimes called a top-level declaration. Additionally, the clause can contain one or more CTE definitions, as shown in the following syntax:

1

2

3

4

CON [RECURSIVE]

cte_name [(col_name [, col_name] ...)] AND (select_query)

[, cte_name [(col_name [, col_name] ...)] AND (select_query)] ...

top_level_declaration;

If heCONclause contains more than one CTE, you must separate them with commas and give each CTE a unique name, although this only applies in the context ofCONClause. for example twoSELECTStatements can contain CTEs with the same name because a CTE is limited to the scope of its associated top-level statement.

CTE names are followed by one or more optional column names, then theANDkeyword and finally aSELECTQuery enclosed in parentheses. If you specify column names, their number must match the number of columns returned bySELECTQuery. If you do not specify column names, the column names returned by theSELECTqueries are used.

Common table expressions are generally used withSELECTTestify. However, you can also use them withTO UPDATEyCLEARDeclarations that follow the same syntax as the previous ones. Additionally, you can include CTEs in your subqueries when passing them to your external statements. You can also use CTE in statements that support the use ofSELECTas part of the statement definition. For example, you can add aCONclause aSELECTconsultation in oneINSERT... SELECTstatement or in aTO CREATE TABLE... SELECTExpression.

In this article, I will mainly focus on creating CTEs that useSELECTstatements as its top-level statements, since that's the most common way to use a CTE. This approach is also a good way to get familiar with CTEs without compromising the data. You can then apply the basic principles you learn here to other types of returns as you become more familiar with how CTEs work.

With that in mind, let's start with a simple example. MonitoringSELECTstatement contains aCONclause that defines a CTE namedplanes:

1

2

3

4

5

6

CON planes AND

(SELECT airplane, engine_account, maximum weight

VON planes WO type of motor = 'Jet');

SELECT airplane, maximum weight VON planes

SERIE VON maximum weight DESCRIPTION;

DieSELECTConsultation in the CTE retrieves all the aircraft in theplanestable that hasJetAs thetype of motor. The CTE result set consists of the data returned bySELECTSee and can be accessed from the upper levelSELECTExpression.

The top-level statement retrieves the data directly from the CTE, similar to how a statement can retrieve data from a view. The main difference is that the view definition is stored in the database and can be used by anyone with the proper permissions. The CTE, on the other hand, is very limited in scope and can only be called in the context of the top-level statement.

In this case the top levelSELECTstatement only retrieves theairplaneymaximum weightColumns of the CTE and orders the results bymaximum weightcolumn in descending order. The following image shows the results returned by the statement.

Introduction to the MySQL Common Table Expression - Simple Talk (1)

(Video) Our Most Power Query Yet! Recursive CTE's (Common Table Expressions)

You can of course get the same results without using a CTE by looking at theplanesDirect table:

1

2

3

4

SELECT airplane, maximum weight

VON planes

WO type of motor = 'Jet'

SERIE VON maximum weight DESCRIPTION;

However, I wanted to show the basic components that are part of a CTE and how you can access that CTE from the top level.SELECTExpression. Both the CTE and the high-level statement certainly can be, and usually are, much more complex, but the principles remain the same.

Work with high level CTESELECTexpression

As mentioned above, a CTE is basically a named result set. When you query the CTE within the top-level statement, the data is returned in a tabular format, similar to what you get when you query a view, permanent table, temporary table, or derived table (such as queries generated by a subquery ) in oneSELECTexpressionVONClause). This means that you can work with the CTE just like you can with these other types of objects. For example, a common approach to referencing a CTE within a top-level query is to join it to another table, as in the following example:

1

2

3

4

5

6

7

CON mfcs AND

(SELECT supplier identification, Manufacturer VON Manufacturer)

SELECT a.airplane, metro.Manufacturer, a.maximum weight

VON planes a INDOOR JOIN mfcs metro

AND a.supplier identification = metro.supplier identification

WO a.type of motor = 'Jet'

SERIE VON a.maximum weight DESCRIPTION;

DieCONclause defines a single CTE namedmfcs. The CTEsSELECTQuery returns thesupplier identificationyManufacturervalues ​​of theManufacturerDesk. the upper levelSELECTthe statement then binds to thatplanestable amfcsCTE, based on thesupplier identificationcolumn in each. The following figure shows the results of the statement.

Introduction to the MySQL Common Table Expression - Simple Talk (2)

As this example shows, you can treat the CTE like any other table structure in your top-level query. However, as you've already seen, you can also rephrase this statement without a CTE by joining theplanestable directly toManufacturerTisch:

1

2

3

4

5

SELECT a.airplane, metro.Manufacturer, a.maximum weight

VON planes a INDOOR JOIN Manufacturer metro

AND a.supplier identification = metro.supplier identification

WO a.type of motor = 'Jet'

SERIE VON a.maximum weight DESCRIPTION;

Because there is so little data, the performance difference between the two statements is negligible, but that may not be the case with a much larger data set. However, as is often the case with MySQL, it can be hard to know which approach is better without comparing both statements against a realistic data set. Even then, there may not be a significant difference in performance, in which case it could be down to developer preference.

As mentioned above, MySQL often supports multiple ways to achieve the same results, as shown in the examples above. Common table expressions can sometimes help simplify code and make it more readable, which is a great benefit, but performance should generally be the primary consideration.

Comparing different approaches usually requires you to test them on a valid data set, in part because it can be difficult to find specific recommendations when comparing approaches. For example, not many database developers would be willing to say that you should do this.foreverUse CTE instead of inner joinsacircumstances or vice versa.

However, you may find recommendations that are less rigid and perhaps worth considering, e.g. B. when comparing CTEs with subqueries. For example, a CTE is often considered a better option ifSELECTcontains multiple subqueries that retrieve the same data, as in the following example:

1

2

3

4

5

6

7

8

9

SELECT supplier identification, plane_id, airplane, maximum weight,

(SELECT RONDA(average(maximum weight)) VON planes a2

WO a.supplier identification = a2.supplier identification) AND average weight,

(maximum weight - (SELECT RONDA(average(maximum weight)) VON planes a2

WO a.supplier identification = a2.supplier identification)) AND amt_over

VON planes a

WO maximum weight >

(SELECT RONDA(average(maximum weight)) VON planes a2

WO a.supplier identification = a2.supplier identification);

If that statement sounds familiar to you, it's because I took it outmy previous article in this series, which deals with subqueries.As you can see, the statement contains three subqueries, all the same, which can result in significant redundant processing depending on how the query is processed by the database engine. The following figure shows the results returned by this statement.

Introduction to the MySQL Common Table Expression - Simple Talk (3)

(Video) What is CTE ( Common Table Expression) in SQL Server ? | SQL Server CTE

Instead of using subqueries, you can achieve the same results by defining a CTE that retrieves the averagemaximum weightvalue for any manufacturer. Then in your top level query you can join thatplanesCTE table with join based on vendor ID, as shown in the following example:

1

2

3

4

5

6

7

8

9

CON mfc_pesos(I would like, average weight) AND

(SELECT supplier identification, RONDA(average(maximum weight))

VON planes GROUP VON supplier identification)

SELECT a.supplier identification, a.plane_id, a.airplane,

a.maximum weight, metro.average weight,

(a.maximum weight - metro.average weight) AND amt_over

VON planes a INDOOR JOIN mfc_pesos metro

AND a.supplier identification = metro.I would like

WO maximum weight > metro.average weight;

In this case, the CTE specifies the column names to be used for the result set, that is, thesupplier identificationThe values ​​are returned asI would likePillar. In addition, the CTE groups the data in theManufacturertable through thesupplier identificationvalues ​​and returns the averageaverage weightvalue for all.

The top-level query then follows the top-level query.planesCTE table, but limits the results to those aircraft withmaximum weightValue greater than the average weight returned by CTE. Notice that the statement now uses instead of subqueriesaverage weightSpalte vom CTE.

Again, the performance difference between these two approaches is negligible since we're working with such a small data set. Only by comparing the statements to a more realistic data set can we get a true picture of their performance differences. However, in my opinion, the CTE makes the code more readable, ie. h it is easier to follow the logic of the instruction.

Define multiple CTEs in oneCONclause

Up to this point, the examples in this article only included one CTE perCONclause, but you can define multiple CTEs and reference each of them in your top-level declaration. Just be sure to give the CTEs different names and separate them with commas. For example the followingCONclause defines three CTEs, all of which are referenced at the top levelSELECTExpression:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

quince

CON

Jets AND

(SELECT airplane, type of motor, engine_account, maximum weight

VON planes WO type of motor = 'Jet'),

Turbos AND

(SELECT airplane, type of motor, engine_account, maximum weight

VON planes WO type of motor = 'Turboprop'),

pistons AND

(SELECT airplane, type of motor, engine_account, maximum weight

VON planes WO type of motor = 'pistons')

SELECT * VON Jets

UNION A

SELECT * VON Turbos

UNION A

SELECT * VON pistons;

The three CTEs are similar, except that each extracts data based on the other.type of motorWorth. the upper levelSELECTQuery then uses theUNIONoperators to join them completely. (HeUNION ALLThe operator combines the results of severalSELECTstatements in a single result set). The following figure shows part of the results returned by this statement.

Introduction to the MySQL Common Table Expression - Simple Talk (4)

This is a fairly simple example, but it demonstrates the concept of defining multiple CTEs and referencing them in the top-level query. In this case, the three CTEs work independently, but it is not always necessary to do so. For example, himCONThe following example clause also contains three CTEs, but in this case the second CTE is (mfc_avg) refers to the first CTE (mfcs), while the third CTE (pl_avg) Being alone:

1

2

3

4

5

6

7

8

9

10

11

12

13

CON

mfcs(I would like, mfc) AND

(SELECT supplier identification, Manufacturer VON Manufacturer),

mfc_avg(I would like, mfc, avg_parking) AND

(SELECT metro.I would like, metro.mfc, RONDA(average(a.Parking lot))

VON mfcs metro INDOOR JOIN planes a

AND metro.I would like = a.supplier identification

GROUP VON supplier identification),

pl_avg(avg_all) AND

(SELECT RONDA(average(Parking lot)) VON planes)

SELECT I would like, mfc, avg_parking

VON mfc_avg metro

WO avg_parking > (SELECT avg_all VON pl_avg);

As this example shows, a CTE can reference a CTE that precedes it. However, this only works one way; a CTE cannot refer to one that follows it. In this case themfc_avgCTE agreesplanestable amfcsCTE and groups the data based on thatsupplier identificationWorth. The top-level query then retrieves data from that CTE, but only returns the rows with aavg_parkingValue greater than that returned by the averagepl_avgCTE. The following figure shows the results returned by this statement.

Introduction to the MySQL Common Table Expression - Simple Talk (5)

It should be emphasized that theWOclause in the top-level query contains a subquery that retrieves data from thepl_avgCTE. This not only points to the inherent flexibility of CTEs, but also to the fact that CTEs and subqueries are not mutually exclusive.

Working with recursive CTEs

One of the most useful aspects of the CTE is its ability to perform recursive queries. This type of CTE, known as a recursive CTE, is one that references itself within the CTE query. theCONclause in a recursive CTE must contain theRECURSIVEkeyword, and the CTE query must contain two parts separated by theUNIONOperator. The first (non-recursive) part fills an initial row of data, and the second (recursive) part does the actual recursion based on that first row. Only the recursive part can refer to the CTE itself.

To understand how this works, consider the following example, which generates a list of even numbers up to and including 20:

1

2

3

4

5

CON RECURSIVE worktop(Wert) AND

(SELECT 2

UNION A

SELECT Wert + 2 VON worktop WO Wert < 20)

SELECT * VON worktop;

(Video) Common Table Expressions and Window Functions simple, maintainable, fast queries

The name of the CTE isworktop, and only the return remainsWertPillar. The non-recursive part of the CTE query sets the value of the first row2, which is assigned to theWertPillar. The recursive part of the query retrieves the data from the CTE but increments theWertcolumn after2with each iteration. The consultation continues to increaseWertcolumn after2as long asWertit's less than20. the upper levelSELECTThe statement then retrieves the data from the CTE and returns the results shown in the following figure.

Note: Since the recursive query says < 20, you might think it wouldn't return 20 on the output. But the iteration that returns 20 occurs, but it stops iterating because the value is no longer less than 20.

Introduction to the MySQL Common Table Expression - Simple Talk (6)

When creating a recursive CTE, keep in mind that MySQL places several restrictions on the recursive part. The secondSELECTdeclaration must not contain aggregate functions, window functionsDISTINGUISHABLEsignal or theGROUP VONoSERIE VONClause.

Running a recursive query can be useful when working with hierarchical data. To demonstrate how this works, I used the following code to create and populate a table calledairline_emps, which stores the IDs and job titles of a group of fictitious employees, along with the ID of the person each reports to:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

quince

sixteen

17

18

19

20

21

22

23

24

25

26

27

28

TO CREATE TISCH airline_emps(

emp_id AND T NOT SIGNED NO NULL,

job title varchar(50) NO NULL,

reported in AND T NOT SIGNED NULL,

Creation date TIME STAMP NO NULL ORIGINALLY CURRENT DATE AND TIME,

last update TIME STAMP NO NULL

ORIGINALLY CURRENT DATE AND TIME AND TO UPDATE CURRENT DATE AND TIME,

PRIMARY WRENCH (emp_id),

FORCE fk_emp_id FOREIGN WRENCH (reported in)

REFERENCES airline_emps(emp_id) );

INSERTION IN airline_emps

(emp_id, job title, reported in)

VALUES

(1, "big boss", NULL),

(2, "Division Manager", 1),

(3, 'In sight', 2),

(4, 'Cook', 2),

(5, 'Designer', 3),

(6, 'senior executive', 1),

(7, 'supervisor', 6),

(8, 'Squad Leader', 6),

(9, 'Organizer', 8),

(10, 'Standards', 8),

(11, 'Specialist', 10),

(12, 'Analyst', 9);

SELECT * VON airline_emps;

everything exceptemp_id 1(Big Boss) reports to someone else. For example, the supervisor reports to the top executive, who in turn reports to the big boss. i included oneSELECTstatement along with theINSERTIONso you can review the data after adding it to the table.

Using this data, you can now create the following recursive CTE that finds each person's position level in the organization and how that position fits into the reporting hierarchy:

1

2

3

4

5

6

7

8

9

10

11

12

13

CON RECURSIVE emp AND

(SELECT emp_id, job title, reported in,

1 AND emp_tier, TO WATER(emp_id AND CHAR(50)) AND rec_route

VON airline_emps

WO reported in ES NULL

UNION A

SELECT a.emp_id, a.job title, a.reported in,

mi.emp_tier + 1,

KONKAT(a.emp_id, ' / ', mi.rec_route)

VON airline_emps a INDOOR JOIN emp mi

AND a.reported in = mi.emp_id)

SELECT * VON emp

SERIE VON emp_tier, emp_id;

Since this is a recursive CTE, it is split into two parts connected withUNION ALLOperator. The non-recursive part fills the first line based on theNULLvalue in thereported inPillar. This series is for the big boss at the top of the pecking order. The non-recursive part also assigns the value1For himemp_tierColumn and arrange theemp_idvalue in therec_routecolumn, converting the value to theCHARtype of data. The first row returned by the CTE is similar to the following figure.

Introduction to the MySQL Common Table Expression - Simple Talk (7)

The recursive part of the CTE uses an inner join to match theairline_empstable aempCTE. The union is based onreported incolumn in theairline_empstable and theemp_idcolumn in theempCTE. The join condition makes it possible to recursively traverse each level of the report hierarchy based onreported inWorth. The recursive part then increases theemp_tiercolumn after1with each new level in the hierarchy.

For example,emp_id 2(head of department) andemp_id 6(Top Executive) both report directlyemp_id 1(Big Boss), die tooemp_tierThe column for these two rows is incremented by1, resulting in a value of2For each row. This means that they are both at the second level of the employee hierarchy. The next level in the hierarchy are the people who report to the division head or senior manager, that is, theemp_tierThe column for these rows is set to3. This process continues until there are no more layers left.

During this process, therec_routeThe column is also updated on each row by concatenating theemp_idtickets to provide a representation of the reporting hierarchy. For example, himreported incolumn foremp_id 9will show that the host is in contactemp_id 8(team leader) who reports toemp_id 6(Senior Executive) who reports toemp_id 1(Big Boss), with each level separated by a slash. The following image shows the data returned by the query.

Introduction to the MySQL Common Table Expression - Simple Talk (8)

the upper levelSELECTThe statement retrieves data from the CTE only without joining other tables. The statement also includes aSERIE VON-Clause that orders the results by firstemp_tiercolumn and then through theemp_idPilar.

Using CTE with DML statements

Earlier in this article, I mentioned that you can use CTEs with statements other thanSELECT. I also explained that my focus in this article was mainly how to implement the CTE withSELECTExpression. However, I want to show you at least one of the alternative ways to give you an idea of ​​what it would look like (and to whet your appetite).

(Video) SQL for Analytics & Data Science | Common Table Expression in MYSQL | StepUp Analytics

The following example shows a CTE used with aTO UPDATEInstruction to change the data in theairline_empsTable created in the previous section:

1

2

3

4

5

6

CON rpts AND

(SELECT emp_id VON airline_emps

WO reported in = 8)

TO UPDATE airline_emps

TO ADJUST reported in = 7

WO emp_id IN (SELECT * VON rpts);

DieCON-clause and CTE work just like you've seen in other examples. The clause contains a single CTE namedrptswho calls thememp_idValues ​​for the employees they report toemp_id 8. The query returns the values.9y10.

the upper levelTO UPDATEstatement uses the data returned by the CTE to update thereported incolumn too7for these two employees. theTO UPDATEexpressionWOcontains a subquery that retrieves the data from the CTE, so the statement only updates those two rows.

After running this update statement, you can run againSELECTStatement from the previous section to verify the changes. I have included the explanation here for your convenience:

1

2

3

4

5

6

7

8

9

10

11

12

13

CON RECURSIVE emp AND

(SELECT emp_id, job title, reported in,

1 AND emp_tier, TO WATER(emp_id AND CHAR(50)) AND rec_route

VON airline_emps

WO reported in ES NULL

UNION A

SELECT a.emp_id, a.job title, a.reported in,

mi.emp_tier + 1,

KONKAT(a.emp_id, ' / ', mi.rec_route)

VON airline_emps a INDOOR JOIN emp mi

AND a.reported in = mi.emp_id)

SELECT * VON emp

SERIE VON emp_tier, emp_id;

The statement returns the results shown in the following figure.

Introduction to the MySQL Common Table Expression - Simple Talk (9)

Please note that the staff9y10now shows areported invalue of7. Additionallyrec_routeThe value in each of the two rows has been updated to reflect the new reporting hierarchy.

Working with general expressions of MySQL tables

The CTE can be a powerful tool when querying and manipulating data in your MySQL databases. Recursive CTEs can be particularly useful when working with self-referential data, as the previous examples have shown. However, CTEs are not always intuitive and you should have a good understanding of how they work before adding them to your existing database code, especially if you intend to use them to manipulate data. For this reason, I recommend you check them out as well.MySQL-Documentationin CTE, along with any other resources available to you. The more time you spend learning about CTEs in advance, the more effectively you can use them in your MySQL queries.

Appendix: Preparation of the objects and demo data

For the examples in this article, I have theto traveldatabase and added theManufactureryplanesto the database. If you want to try these examples yourself, first run the following script on your MySQL instance:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

quince

sixteen

17

18

19

20

21

22

23

24

25

26

27

RELEASE DATABASE AND GIFT to travel;

TO CREATE DATABASE to travel;

USE to travel;

TO CREATE TISCH Manufacturer(

supplier identification AND T NOT SIGNED NO NULL,

Manufacturer VARCHAR(50) NO NULL,

Creation date TIME STAMP NO NULL ORIGINALLY CURRENT DATE AND TIME,

last update TIME STAMP NO NULL

ORIGINALLY CURRENT DATE AND TIME AND TO UPDATE CURRENT DATE AND TIME,

PRIMARY WRENCH (supplier identification) );

TO CREATE TISCH planes(

plane_id AND T NOT SIGNED NO NULL,

airplane VARCHAR(50) NO NULL,

supplier identification AND T NOT SIGNED NO NULL,

type of motor VARCHAR(50) NO NULL,

engine_account TINYINT NO NULL,

maximum weight INT MIDDLE NOT SIGNED NO NULL,

lapse DECIMAL(5,2) NO NULL,

plane_length DECIMAL(5,2) NO NULL,

Parking lot AND T GENERATED FOREVER AND ((lapse * plane_length)) STORED,

code_icao CHAR(4) NO NULL,

Creation date TIME STAMP NO NULL ORIGINALLY CURRENT DATE AND TIME,

last update TIME STAMP NO NULL

ORIGINALLY CURRENT DATE AND TIME AND TO UPDATE CURRENT DATE AND TIME,

PRIMARY WRENCH (plane_id),

FORCE fk_manufacturer_id FOREIGN WRENCH (supplier identification)

REFERENCES Manufacturer(supplier identification) );

After creating the database, you can add sample data to itManufacturertable by running the followingINSERTIONstatement that inserts seven lines:

1

2

3

4

INSERTION IN Manufacturer(supplier identification, Manufacturer)

VALUES (101,'Airbus'), (102,'Aviones Beagle Limited'), (103,'Beechcraft'),

(104,'Boeing'), (105,'Bombardier'), (106,'Cessna'), (107,'Embraer');

SELECT * VON Manufacturer;

i included oneSELECTstatement afterINSERTIONstatement so you can confirm that all seven rows have been added to the table. The first row of the table has asupplier identificationvalue of101, and subsequent lines are incremented by one. After you have filled theManufacturertable you can do the followingINSERTIONInstructions for adding data toplanesTisch:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

quince

sixteen

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

INSERTION IN planes

(plane_id, airplane, supplier identification, type of motor, engine_account,

lapse, plane_length, maximum weight, code_icao)

VALUES

(1001,'A340-600',101,'Jet',4,208.17,247.24,837756,'A346'),

(1002,"ONLY A350-800",101,'Jet',2,212.42,198.58,546700,'A358'),

(1003,'A350-900',101,'Jet',2,212.42,219.16,617295,'A359'),

(1004,'A380-800',101,'Jet',4,261,65,238.62,1267658,'A388'),

(1005,'A380-843F',101,'Jet',4,261,65,238.62,1300000,'A38F'),

(1006,'A.109 Airedale',102,'pistons',1,36.33,26.33,2750,'AIRE'),

(1007,'A.61-Terrier',102,'pistons',1,36,23.25,2400,'AUS6'),

(1008,'B.121 Welpe',102,'pistons',1,31,23.17,1600,'PUPPY'),

(1009,'B.206',102,'pistons',2,55,33.67,7500,'UNDER'),

(1010,'D.5-108 Husky',102,'pistons',1,36,23.17,2400,'D5'),

(1011,'Baron 56 TC Turbo-Baron',103,'pistons',2,37.83,28,5990,'BE56'),

(1012,'Baron 58 (and current G58)',103,'pistons',2,37.83,29.83,5500,'BE58'),

(1013,'Beechjet 400 (as MU-300-10 Diamond II)',103,'Jet',2,43.5,48.42,15780,'BE40'),

(1014,Bonanza 33 (F33A),103,'pistons',1,33.5,26.67,3500,'BE33'),

(1015,Bonanza 35 (G35),103,'pistons',1,32.83,25.17,3125,'BE35'),

(1016,'747-8F',104,'Jet',4,224.42,250.17,987000,'B748'),

(1017,'747-SP',104,'Jet',4,195.67,184,75,696000,'B74S'),

(1018,'757-300',104,'Jet',2,124,83,178.58,270000,'B753'),

(1019,'767-200',104,'Jet',2,156.08,159.17,315000,'B762'),

(1020,'767-200ER',104,'Jet',2,156.08,159.17,395000,'B762'),

(1021,'Learjet 24',105,'Jet',2,35.58,43.25,13000,'LJ24'),

(1022,'Learjet 24A',105,'Jet',2,35.58,43.25,12499,'LJ24'),

(1023,'Challenger (BD-100-1A10) 350',105,'Jet',2,69,68,75,40600,'CL30'),

(1024,'Challenger (CL-600-1A11) 600',105,'Jet',2,64.33,68.42,36000,'CL60'),

(1025,'Challenger (CL-600-2A12) 601',105,'Jet',2,64.33,68.42,42100,'CL60'),

(1026,'414A Canciller',106,'pistons',2,44.17,36.42,6750,'C414'),

(1027,'421C Steinadler',106,'pistons',2,44.17,36.42,7450,'C421'),

(1028,'425 Corsair Conquest I',106,'Turboprop',2,44.17,35.83,8600,'C425'),

(1029,'441 Conquest II',106,'Turboprop',2,49.33,39,9850,'C441'),

(1030,'Quote CJ1 (Model C525)',106,'Jet',2,46.92,42.58,10600,'C525'),

(1031,'EMB 175 LR',107,'Jet',2,85.33,103.92,85517,'E170'),

(1032,'EMB 175 standard',107,'Jet',2,85.33,103.92,82673,'E170'),

(1033,'EMB 175-E2',107,'Jet',2,101.67,106,98767,'E170'),

(1034,'EMB 190 AR',107,'Jet',2,94.25,118.92,114199,'E190'),

(1035,'EMB 190 LR',107,'Jet',2,94.25,118.92,110892,'E190');

SELECT * VON planes;

(Video) Representing Hierarchies with T-SQL Recursive Common Table Expressions

DieINSERTIONstatement uses thesupplier identificationvalues ​​of theManufacturerDesk. These values ​​provide the foreign key values ​​necessary for thesupplier identificationcolumn in theplanesDesk. Also, the front row is taken1001For himplane_idvalue with whichplane_idThe values ​​for the other rows increased accordingly. As with the predecessorINSERTIONExplanation, I inserted aSELECTStatement confirming that the data has been added correctly.

FAQs

What is common table expression MySQL? ›

A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times.

Why would you use a common table expression MySQL? ›

A CTE provides better readability and also increases the performance as compared to the derived table. Unlike a derived table, a CTE is a subquery that can be self-referencing using its own name. It is also known as recursive CTE and can also be referenced multiple times in the same query.

Can we write CTE in MySQL? ›

In MySQL every query generates a temporary result or relation. In order to give a name to those temporary result set, CTE is used. A CTE is defined using WITH clause. Using WITH clause we can define more than one CTEs in a single statement.

What version of MySQL has CTE? ›

Common table expressions (CTEs) are a great way to break up complex queries. MySQL started supporting this in version 8. Here's a simple query to illustrate how to write a CTE: with beta_users as ( select * from users where beta is true ) select events.

What is the purpose of common table expression? ›

CTEs, like database views and derived tables, enable users to more easily write and maintain complex queries via increased readability and simplification. This reduction in complexity is achieved by deconstructing ordinarily complex queries into simple blocks to be used, and reused if necessary, in rewriting the query.

What are common table EXPRESSIONs? ›

A common table expression, or CTE, is a temporary named result set created from a simple SELECT statement that can be used in a subsequent SELECT statement. Each SQL CTE is like a named query, whose result is stored in a virtual table (a CTE) to be referenced later in the main query.

What is CTE in SQL with example? ›

What is CTE in SQL Server? A CTE (Common Table Expression) is a one-time result set that only exists for the duration of the query. It allows us to refer to data within a single SELECT, INSERT, UPDATE, DELETE, CREATE VIEW, or MERGE statement's execution scope.

What are the benefits of CTE in SQL? ›

CTE benefits
  • CTEs make code more readable. And readability makes queries easier to debug.
  • CTEs can reference the results multiple times throughout the query. By storing the results of the subquery, you can reuse them throughout a larger query.
  • CTEs can help you perform multi-level aggregations.

When should you use a CTE SQL? ›

A CTE can be used to: Create a recursive query. For more information, see Recursive Queries Using Common Table Expressions. Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.

Why use CTE instead of temp table? ›

It is a temporary result set and typically it may be a result of complex sub-query. Unlike the temporary table, its life is limited to the current query. It is defined by using WITH statement. CTE improves readability and ease in maintenance of complex queries and sub-queries.

What is TMD MySQL? ›

The . TMD file is an intermediate data file for a table that needs to recreate its data file. So you can remove it because it's normally used as a temporarly file but you could rename the file and check what happens just in case.

What are CTE and derived tables? ›

CTEs were introduced back in SQL Server 2005. While there is some additional functionality, i.e. recursion, CTEs work similarly to derived tables. Derived tables are subqueries that are used in the FROM clause instead of named tables. I like using CTEs over derived tables because CTEs are so much easier to read.

What is difference between temporary table and Common Table Expression CTE in SQL? ›

Probably the biggest difference between a CTE and a temp table, is that the CTE has an execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. Essentially you can't reuse the CTE, like you can with temp tables.

Videos

1. Bruce Momjian: Programming the SQL Way with Common Table Expressions
(Postgres Open)
2. Derived tables and common table expressions in sql server Part 48
(kudvenkat)
3. Fearless SQL - Introduction to Recursive Common Table Expression
(Essential SQL)
4. What's all this fuss about Common Table Expressions (CTE's) anyway?
(PostgresConf South Africa)
5. MySQL Tutorial for Beginners [Full Course]
(Programming with Mosh)
6. SQL WITH Clause with examples | SQL CTE (Common Table Expression) | SQL Tutorial in Hindi 16
(Rishabh Mishra)

References

Top Articles
Latest Posts
Article information

Author: Rob Wisoky

Last Updated: 22/08/2023

Views: 5960

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.