In order to combine two or more result sets into one, and thus increase readability and speed up querying, the UNION operator may be used.

Syntax

The basic syntax explaining how to do it is shown here:

SELECT column1, column2 FROM table1 UNION [DISTINCT | ALL]

SELECT column1, column2 FROM table2 UNION [DISTINCT | ALL];

The main rules are to make the number of columns equal, and to keep the data types equal as well.

The operator DISTINCT is a default so if it gets omitted, the query will 'pretend' that only distinct values end up combined.

We can see the most realistic example that combines SELECT statement with the ORDER BY clause below:

(SELECT itemNumber, itemPrice FROM customers) 

UNION 

(SELECT buyerNumber, buyerName FROM employees) 

ORDER BY 2, 1;

In the example below we put apprentices to group both SELECT statements and group them together. If we want to group them separately, we should drop the apprentices and put ORDER BY clause behind each of the statements.