The SQL UNION Operator (Works in MySQL as well)
As per the name suggests, UNION operator merges/combines/joins two or more results of SELECT statements. But you have to be careful while joining the result sets as it has to follow some conditions. For example,
- You have to select same number of columns for each select statements. It makes sense. You can’t merge 1 column with 2 different columns data. Right?
- Those columns MUST have same data type. For example, you can’t join columns with INT and VARCHAR data types.
- The columns needs to be (read as MUST be) in the same order. For example if there are two columns; city column from customer and city column from merchants, which you want to join then it should be in the exact same order in the table. That’s tough one!
Let’s take a look at the syntax:
SELECT column(s) FROM table1 UNION SELECT column(s) FROM table2;
The UNION operator by default selects distinct values. Means no place or duplicate values. For example, if there is a Chicago in a city columns of customers and merchants both then it will only give us one Chicago city in result set.
To allow duplicates, use UNION ALL. For e.g.
SELECT column(s) FROM table1 UNION ALL SELECT column(s) FROM table2;
Let’s take a look at the example.
SELECT City FROM Customers UNION SELECT City FROM merchants ORDER BY City;
The example query above will give us all the cities list which are in the city column of Customers table as well as in merchants table.
database sql operators sql query UNION