MySQL Unions
Union operator
Section titled “Union operator”The UNION operator is used to combine the result-set (only distinct values) of two or more SELECT statements.
Query: (To selects all the different cities (only distinct values) from the “Customers” and the “Suppliers” tables)
SELECT City FROM CustomersUNIONSELECT City FROM SuppliersORDER BY City;Result:
Number of Records: 10
City------AachenAlbuquerqueAnchorageAnnecyBarcelonaBarquisimetoBendBergamoBerlinBernUnion ALL
Section titled “Union ALL”UNION ALL to select all (duplicate values also) cities from the “Customers” and “Suppliers” tables.
Query:
SELECT City FROM CustomersUNION ALLSELECT City FROM SuppliersORDER BY City;Result:
Number of Records: 12
City-------AachenAlbuquerqueAnchorageAnn ArborAnnecyBarcelonaBarquisimetoBendBergamoBerlinBerlinBernUNION ALL With WHERE
Section titled “UNION ALL With WHERE”UNION ALL to select all(duplicate values also) German cities from the “Customers” and “Suppliers” tables.
Here Country="Germany" is to be specified in the where clause.
Query:
SELECT City, Country FROM CustomersWHERE Country='Germany'UNION ALLSELECT City, Country FROM SuppliersWHERE Country='Germany'ORDER BY City;Result:
Number of Records: 14
```sql|City|Country|Aachen|Germany|Berlin|Germany|Berlin|Germany|Brandenburg|Germany|Cunewalde|Germany|Cuxhaven|Germany|Frankfurt|Germany|Frankfurt a.M. |Germany|Köln|Germany|Leipzig|Germany|Mannheim|Germany|München|Germany|Münster|Germany|Stuttgart|Germany
#### Syntax
- SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;<li>SELECT column_name(s) FROM table1UNION ALLSELECT column_name(s) FROM table2;</li><li>SELECT column_name(s) FROM table1WHERE col_name="XYZ"UNION ALLSELECT column_name(s) FROM table2WHERE col_name="XYZ";</li>
#### Remarks
`UNION DISTINCT` is the same as `UNION`; it is slower than `UNION ALL` because of a de-duplicating pass. A good practice is to always spell out `DISTINCT` or `ALL`, thereby signaling that you thought about which to do.