SQL UNION Operator

SQL UNION operator is used to combine the results of two or more SELECT statements. Each SELECT statement within the UNION must have the same number of columns and all columns should have same order with similar data types. Union operator is different JOINs which is also used to combine results of two or more tables.

 

Syntax

SELECT column1, column2, column3,…columnN FROM tableName1
UNION
SELECT column1, column2, column3,…columnN FROM tableName2

Here is our first table Student.

StudentTableUnion

We have second table as NewStudents.

StudentTableUnion2

Now, we will use UNION operator to combine records of both the tables StudentNewStudents.

So, here is the output.

SELECT *FROM Student
UNION
SELECT *FROM NewStudents

Union

Similarly, you can combine specific columns columns from two tables as given below.

SELECT RollNumber, FirstName, Country, Fees FROM Student
UNION
SELECT RollNumber, FirstName, Country, Fees FROM NewStudents

UnionColumns

Note: SQL UNION operator returns only distinct values by default. To allow all duplicate values, you can use UNION ALL operator.

Reference: Manzoor Siddiqui [www.SQLServerLog.com]

You may also like

You may also like...

Leave a Reply