An Essential Guide to MySQL Derived Table?
Summary: in this tutorial, you will learn about the MySQL derived table and how to it to simplify complex queries.
Introduction to MySQL derived table
A derived table is a virtual table returned from a
SELECT
statement. A derived table is similar to a temporary table, but using a derived table in the SELECT
statement is much simpler than a temporary table because it does not require steps of creating the temporary table.
The term derived table and subquery is often used interchangeably. When a stand-alone subquery is used in the
FROM
clause of a SELECT
statement, we call it a derived table.
The following illustrates a query that uses a derived table:
Note that a stand-alone subquery is a subquery which can execute independently of the statement containing it.
Unlike a subquery, a derived table must have a an alias so that you can reference its name later in the query. If a derived table does not have an alias, MySQL will issue the following error:
The following illustrates an SQL statement that uses a derived table:
A simple MySQL derived table example
The following query gets the top 5 products by sales revenue in 2003 from the
orders
and orderdetails
tables in the sample database:
You can use the result of this query as a derived table and join it with the
products
table as follows:
The following shows the output of the query above:
In this example:
- First, the subquery executed to create a result set or derived table.
- Then, the outer query executed that joined the
top5product2003
derived table with theproducts
table using theproductCode
column.
A more complex MySQL derived table example
Suppose you have to classify the customers in the year of 2003 into 3 groups:
platinum
, gold
, and silver
. In addition, you need to know the number of customers in each group with the following conditions:- Platinum customers who have orders with the volume greater than 100K
- Gold customers who have orders with the volume between 10K and 100K
- Silver customers who have orders with the volume less than 10K
To construct this query, first, you need to put each customer into the respective group using
CASE
expression and GROUP BY
clause as follows:
The following is the output of the query:
Then, you can use this query as the derived table and perform grouping as follows:
The query returns the customer groups and the number of customers in each.
In this tutorial, you have learned how to use the MySQL derived tables which are subqueries in the FROM clause to simplify complex queries.
0 comments:
Post a Comment