UNION

DaniB
2 min readDec 9, 2019

--

SQL is a very important language that developers use on a daily basis. The capacity this language has for selecting data from databases is astounding. There is so much you can to do with SQL that it would be best to discuss each built in method one by one.

One of these methods is UNION. according to W3Scool

“The UNION operator is used to combine the result-set of two or more SELECT statements.

Each SELECT statement within UNION must have the same number of columns

The columns must also have similar data types

The columns in each SELECT statement must also be in the same order”

This means that you can list out a large number of data from different tables and different columns into one large list.

Lets take this example data from https://pgexercises.com/ (which is a fantastic resource for practicing PostgreSQL)

here we have three different tables with a number of different columns. In the exercise we are given the challenge to joining all the surnames from the members table and all the names from the facilities tables.

we do this simply by putting two different SQL queries together simply by using the key word UNION

like so

which will output- note there will be no repeats in this output

(the list goes on)

If we wanted to make sure we got every output including the duplicate all we would have to do is add the word ALL after UNION

and there you have- a simple union!

--

--