SELECT
statement used in the UNION
operator must have an equal number of columns.SELECT
statement must also have the same order.SELECT column(s)
FROM first_table
UNION
SELECT column(s)
FROM second_table;
ConsumerID | Name | City | Country |
1 | Ethan Goldberg | NewYork | U.S.A |
2 | John Snow | Berlin | Germany |
3 | Saad Qurshi | Ontario | Canada |
4 | Amir Iqbal | Paris | France |
5 | Dania Khan | Bowling Green | U.S.A |
6 | Yousaf Khan | Tenesse | U.S.A |
ProducerID | Name | City | Country |
1 | Amazon | NewYork | U.S.A |
2 | Walmart | Berlin | Germany |
3 | TacoBell | Ontario | Canada |
4 | Walmart | NewYork | U.S.A |
5 | MercedsBenz | Frankfurt | Germany |
6 | BMW | Berlin | Germany |
CREATE DATABASE test;CREATE TABLE Consumers (ConsumerID int,ConsumerName varchar(20),City varchar(20),Country varchar(20));INSERT INTO ConsumersVALUES (1, 'Ethan Goldberg','NewYork','U.S.A');INSERT INTO ConsumersVALUES (2, 'John Snow','Berlin','Germany');INSERT INTO ConsumersVALUES (3, 'Saad Qureshi','Ontario','Canada');INSERT INTO ConsumersVALUES (4, 'Amir Iqbal','Paris','France');INSERT INTO ConsumersVALUES (5, 'Dania Khan','Bowling Green','U.S.A');INSERT INTO ConsumersVALUES (6, 'Yousaf Khan','Tenesse','U.S.A');CREATE TABLE Producers (ProducerID int,PriducerName varchar(20),City varchar(20),Country varchar(20));INSERT INTO ProducersVALUES (1, 'Amazon','NewYork','U.S.A');INSERT INTO ProducersVALUES (2, 'Walmart','Berlin','Germany');INSERT INTO ProducersVALUES (3, 'TacoBell','Ontario','Canada');INSERT INTO ProducersVALUES (4, 'Walmart','NewYork','U.S.A');INSERT INTO ProducersVALUES (5, 'Mercedes-Benz','Franfurt','Germany');INSERT INTO ProducersVALUES (6, 'BMW','Berlin','Germany');SELECT City FROM ConsumersUNIONSELECT City FROM Producers
Note: The
UNION
operator only selects the distinct values from the selected columns.