Unions
Now that we understand how joins work, let’s move on to unions. This is a relatively easy concept.
The UNION keyword is used to combine the results of two or more SELECT statements. Each SELECT statement must have the same number of columns. The syntax is:
SELECT_statement_one
UNION
SELECT_statement_two;
The column names from the first SELECT statement will be used as the column names for the results returned.
Let’s look at an example.
For the employees table, we can do a UNION as follows:
SELECT em_name, salary FROM employees WHERE gender = 'M'
UNION
SELECT em_name, years_in_company FROM employees WHERE gender = 'F';
We’ll get the following output:
The first 5 rows are from the first SELECT statement while the last 4 are from the second statement.
Note that by default, the UNION keyword removes any duplicates from the result. If you...