The purpose of the UNION directive is to combine the results of two SQL statements. From this point of view, UNION is somewhat similar to join, because these two instructions can be retrieved from multiple tables. One limitation of the UNION is that the columns generated by the two SQL statements need to be of the same type of data. Also, when we use the UNION command, we will only see different data values (like SELECT DISTINCT).
The syntax of UNION is as follows:
[SQL statement 1]
UNION
[SQL Statement 2];
Let's say we have the following two tables,
store_information Form
Store_name |
Sales |
Txn_date |
Los Angeles |
1500 |
05-jan-1999 |
San Diego |
250 |
07-jan-1999 |
Los Angeles |
300 |
08-jan-1999 |
Boston |
700 |
08-jan-1999 |
Internet Sales table
Txn_date |
Sales |
07-jan-1999 |
250 |
10-jan-1999 |
535 |
11-jan-1999 |
320 |
12-jan-1999 |
750 |
And we want to find out all the days that have turnover (sales). To achieve this, we use the following SQL statement:
SELECT txn_date from Store_information
UNION
SELECT txn_date from Internet_sales;
Results:
Txn_date |
jan-05-1999 |
jan-07-1999 |
jan-08-1999 |
jan-10-1999 |
jan-11-1999 |
jan-12-1999 |
One thing to note is that if we use SELECT DISTINCT txn_date in any SQL statement (or both), we will get exactly the same result.
Linux measured results:
1. Create a table
2. Inserting table records
3.UNION (+) Two tables
A concise tutorial of SQL statements for Linux---UNION