HOW TO USE UNION IN SQL

UNION in SQL

UNION operator is used to select distinct values from the combination of the result-set of two or more SELECT statements, provided that the data type and the number of fields, and the order of fields must be the same for every SELECT statement. To allow duplicate values in the result set, use UNION ALL.

Syntax of UNION  in SQL-

SELECT <column_name(s)> FROM table1

UNION

SELECT <column_name(s)> FROM table2;

Example of UNION in SQL-

SELECT City FROM Customers

UNION

SELECT City FROM Suppliers;

Syntax of UNION ALL in SQL-

SELECT <column_name(s)> FROM table1

UNION ALL

SELECT <column_name(s)> FROM table2;

Example of UNION ALL in SQL-

SELECT City FROM Customers

UNION ALL

SELECT City FROM Suppliers;

–It will return the cities from both Customers and Suppliers table.


Leave a Reply

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