In some of our other videos on SQL, we cover the basic commands using SQL queries

and how to extract data from multiple tables using joints.

In this short video, we're going to talk about a different way of bringing data

from multiple tables together using the UNION command.

When we learned about joining tables together, we really focused

on how to enrich rows of data by adding columns from different tables.

You can think of this as kind of a left right operation.

We have some data on the left and some data on the right, and

we want to bring them together.

We do this using a joint operation.

We can also think about bringing tables together top to bottom.

Meaning that if we have two sets of data with similar types of rows, we can sort of

stack the data on top of each other to get one taller data set with more rows.

To do this, we use the UNION command.

The syntax of the UNION command looks like this.

Here I have two simple SELECT from clauses with the UNION command between them.

The key requirement for performing a UNION is that the top and

bottom data sets need to have the same number of columns.

And those columns need to represent the same set of ideas in the same order.

So in this case, the type of data in FIELD_A from the top SELECT clause needs

to match the type of data in FIELD_D on the bottom SELECT clause.

The type of data in FIELD_B needs to match the type of data in FIELD_E and

the type of data in FIELD_C needs to match the type of data in FIELD_F.

Note that I said the type of data, not the column name.

The column names do not have to match.

But the type of data in those columns do have to match.

So if FIELD_A is a number then FIELD_D also has to be a number.

If FIELD_C is a date then FIELD_F also has to be a date.

If the column names are different, the SQL engine will generally just use the column

names from the first SELECT statement in the data output.