Sunny Books
What we have

SQL UNION Operator

The UNION operator combines two or more separate SELECT statements into one result set. A JOIN statement adds additional table columns to a result set (horizontally), while UNION combines row results from one table with rows of another table (vertically).

SQL UNION Syntax

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

SQL UNION ALL Syntax

ELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2

Since UNION operator selects table columns from two or more table and put all selected rows together into a result-set with the same number and order of table columns, each SELECT statement within the UNION must satisfy the following conditions:

1. Each SELECT statement must have the same number of columns.

2. The columns must also have similar data types.

3. The columns in each SELECT statement must be in the same order.

4. The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.

5. ORDER BY clause should be used only on the last SELECT statement in the UNION query.

Difference between UNION and UNION ALL:

1. The UNION operator selects only distinct values by default. while UNION ALL selects duplicate values.

2. UNION has to perform distinct sort to remove duplicates, which makes it less faster than UNION ALL

Difference between UNION and JOIN

UNION combines the result set of two or more select queries into a single result-set which includes all the rows from all the queries in the union, while JOINS retrieve data from two or more tables based on logical relationships between the tables.

SUNWEB EXPERT