Friday 13 July 2018

An Essential Guide to MySQL Derived Table


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:

MySQL Derived Table Example 1
You can use the result of this query as a derived table and join it with the products table as follows:
products table
The following shows the output of the query above:
MySQL Derived Table - Top 5 Products 2013
In this example:
  1. First, the subquery executed to create a result set or derived table.
  2. Then, the outer query executed that joined the top5product2003 derived table with the productstable using the productCode column.

A more complex MySQL derived table example

Suppose you have to classify the customers in the year of 2003 into 3 groups: platinumgold, and silver. In addition, you need to know the number of customers in each group with the following conditions:
  1. Platinum customers who have orders with the volume greater than 100K
  2. Gold customers who have orders with the volume between 10K and 100K
  3. 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 CASEexpression and GROUP BY clause as follows:
The following is the output of the query:
MySQL Derived Table - Customer Groups
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.
MySQL Derived Table - Customer Group Counts
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