SQL – Union

Table Of Contents:

  1. What Is SQL Union?
  2. Syntax Of SQL Union.
  3. Examples Of SQL Union.

(1) What Is SQL Union ?

  • The UNION the operator is used to combine the result set of two or more SELECT statements.

  • Every SELECT statement within UNION must have the same number of columns.

  • The columns must also have similar data types

  • The columns in every SELECT statement must also be in the same order

(2) Syntax Of SQL Union ?

Syntax: UNION Syntax

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Syntax: UNION ALL Syntax

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Note:

  • The UNION the operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

(3) Examples Of SQL Union ?

Customer Table:

Suppliers Table:

Example-1: SQL UNION Example

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Example-2: SQL UNION ALL Example

SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

Example-3: SQL UNION With WHERE

SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Example-4: SQL UNION ALL With WHERE

SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Leave a Reply

Your email address will not be published. Required fields are marked *