Database Reference
In-Depth Information
The following example sorts the results returned by the previously used UNION :
Input
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001,1002)
ORDER BY vend_id, prod_price;
Output
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
| 1001 | ANV01 | 5.99 |
| 1001 | ANV02 | 9.99 |
| 1001 | ANV03 | 14.99 |
| 1002 | FU1 | 3.42 |
| 1002 | OL1 | 8.99 |
| 1003 | TNT1 | 2.50 |
| 1003 | FC | 2.50 |
| 1003 | SLING | 4.49 |
+---------+---------+------------+
Analysis
This UNION takes a single ORDER BY clause after the final SELECT statement.
Even though the ORDER BY appears to only be a part of that last SELECT state-
ment, MariaDB in fact uses it to sort all the results returned by all the SELECT
statements.
Note
Combining Different Tables For the sake of simplicity, all the examples in this chap-
ter combined queries using the same table. However, everything you learned here also
applies to using UNION to combine queries of different tables.
Summary
In this chapter, you learned how to combine SELECT statements with the
UNION operator. Using UNION , you can return the results of multiple queries
as one combined query, either including or excluding duplicates. The use of
UNION can greatly simplify complex WHERE clauses and retrieving data from
multiple tables.
 
 
Search WWH ::




Custom Search