Home

Introduction to Unions

Introduction

A union is the operation that consists of combining the values from two tables. In the structured query language (SQL), the operation is performed using the UNION operator. Let’s consider the following table of employees:

Employees Table

 

Employees Table

And the following table of contractors:

Contractors Table

 

Contractors Table

You may know already that you can create a query that includes records of both tables. Here is an example:

Contractors Table

The SQL code of this query is:

SELECT Employees.EmployeeNumber,
       Employees.FirstName, 
       Employees.LastName, 
       Employees.Title, 
       Contractors.ContractorCode, 
       Contractors.FName, 
       Contractors.LName, 
       Contractors.Position
FROM Employees, Contractors;

And the result is:

	  Query Example

Creating a Union

In order to create a union of two tables, the attributes of the tables involved must follow two rules:

Obviously before performing a union on two tables, it must be verified that the tables have the same number of columns and the columns are compatible in each position. If this is established, the tables are said to be compatible.

A union is performed by creating a query that contains the records from the first table followed by the records of the second table, using the respective positions of their columns.

The basic formula to create a union is:

SELECT Fields FROM FirstTable
UNION
SELECT Fields FROM Contractors;

A union of the above tables is:

SELECT Employees.EmployeeNumber,
       Employees.FirstName,
       Employees.LastName,
       Employees.Title
FROM Employees
UNION
SELECT Contractors.ContractorCode,
       Contractors.FName,
       Contractors.LName,
       Contractors.Position
FROM Contractors;

A union of the above tables would produce:

A Union of Two Tables


Home Copyright © 2011-2021, FunctionX Home