UNION

The MySQL UNION operator is used to combine the result-set of two or more SELECT statements. To apply the UNION operator one must remember following things:

  • 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

Syntax:

SELECT <column name(s)> FROM table1
UNION
SELECT <column name(s)> FROM table2;

To allow the duplicate values we use UNION ALL, as UNION operator only returns the distinct values.

SELECT <column name(s)> FROM table1
UNION ALL
SELECT <column name(s)> FROM table2;

The column names in the result-set are usually equal to the column names in the first SELECT statement.

Leave a comment

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started