SQL - Union


Commands Covered


  • SELECT
  • UNION
  • UNION ALL
  • WHERE


Union = Append

UNION is basically SQL’s way to append data from one table to another. UNION is placed between two SELECT statements that return the same type and number of columns.

Generic example:

SELECT column_1
  FROM table_1 
UNION
SELECT column_2
  FROM table_2


As long as column_1 and column_2 are of the same data type (i.e. integers), you’ll be given a singular column that contains unique entries from both of the columns, stacked upon each other.

UNION ALL will return duplicates in this list.

The following example returns all of the cities and countries in which stores and customers are located.

SELECT city, country 
  FROM stores
UNION
SELECT city, country,
  FROM customers


You can think of unions as if you’re stacking data sources on top of one another, as opposed to joins where you’re combining data sources in a horizontal fashion.


That’s all for now!

- Fisher



Comments