For the complete documentation index, see llms.txt. This page is also available as Markdown.

Subqueries in a FROM Clause (Derived Tables)

Use a subquery as a temporary table. Derived tables allow you to select from the result set of another query within the FROM clause.

Although subqueries are more commonly placed in a WHERE clause, they can also form part of the FROM clause. Such subqueries are commonly called derived tables.

If a subquery is used in this way, you must also use an AS clause to name the result of the subquery.

ORACLE mode

MariaDB starting with 10.6.0

Anonymous subqueries in a FROM clause (no AS clause) are permitted in ORACLE mode.

Correlation Column List

MariaDB starting with 11.7.0

From MariaDB 11.7:

It is possible to assign column names in the derived table name syntax element.

Before MariaDB 11.7:

It is not possible to assign column names in the derived table name syntax element.

Examples

CREATE TABLE student (name CHAR(10), test CHAR(10), score TINYINT); 

INSERT INTO student VALUES 
  ('Chun', 'SQL', 75), ('Chun', 'Tuning', 73), 
  ('Esben', 'SQL', 43), ('Esben', 'Tuning', 31), 
  ('Kaolin', 'SQL', 56), ('Kaolin', 'Tuning', 88), 
  ('Tatiana', 'SQL', 87), ('Tatiana', 'Tuning', 83);

Assume that, given the data above, you want to return the average total for all students. In other words, the average of Chun's 148 (75+73), Esben's 74 (43+31), etc.

You cannot do the following:

A subquery in the FROM clause is however permitted:

The following is permitted only in ORACLE mode, where a derived table may omit its alias:

In this example, the second column of the derived table dt is used both within (WHERE c2 > 0), and outside, (WHERE a2 > 10), the specification. Both conditions apply to t1.c2.

This page is licensed: CC BY-SA / Gnu FDL

spinner

Last updated

Was this helpful?