UNION Clause
Swipe to show menu
You've caught the attention of a client who needs SQL queries. Before diving into JOINs, you'll learn about the UNION clause, which is essential for combining multiple tables.
UNION in SQL is used to combine the results of two or more SELECT queries into one resulting set. It allows you to merge rows from multiple queries into a single result set of data.
Here are some important things to know about using UNION:
-
Columns Count and Order: all queries combined with
UNIONmust have the same number of columns in the same order; -
Data Types: the columns in each query must have compatible data types;
-
Unique Rows: by default,
UNIONremoves duplicate rows. UseUNION ALLif you want to keep duplicates.
For a better understanding of how to correctly combine tables using the UNION clause, An additional table that contains information about contractors has been introduced.
There's not much information here, just the first_name, last_name, and email.
You can see that this table has similarities with the employees table. Using the UNION clause, you can combine these two tables to, for example, see a list of all names and surnames of employees and contractors involved in the company.
To do this, you'll use the UNION clause:
12345678(SELECT employee_id as id, first_name, last_name FROM employees) UNION (SELECT contractor_id as id, first_name, last_name FROM contractors) ORDER BY id
There are two queries that each return three columns with the same data types. The goal is to see the Id, first_name, and last_name of everyone in the company. The Id column was also renamed so both queries have the same column names.
UNION combines the results of these queries, removing duplicates (though there are none here).
Finally, the results are sorted by Id using ORDER BY.
The results are sorted by Id, which is a common column in both tables.
After using UNION, you get a "single large query" that you can further manipulate with clauses like ORDER BY.
You can't directly use WHERE or GROUP BY with tables combined using UNION. To apply these clauses, you need to use a subquery in the FROM section. Here's an example of how to do it:
123456789SELECT id, first_name, last_name FROM ( SELECT employee_id AS id, first_name, last_name FROM employees UNION SELECT contractor_id AS id, first_name, last_name FROM contractors ) AS combined WHERE first_name = 'Jane'
Using a subquery in the FROM section gives us more flexibility! It might seem tricky at first, but mastering this will make writing complex queries much easier.
1. What requirements must result sets meet to be combined using UNION?
2. How does the UNION clause treat duplicate rows by default?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat