SQL Union

SQL Union is used to combine the query of two or more Select Statement. The Union Clause is used to return the combine set of records from two tables.

SQL Union

SQL Union

     

SQL Union is used to combine the query of two or more Select Statement. The Union Clause is used to return the combine set of records from two tables.

Understand with Example

The Tutorial illustrate an example from 'SQL Union'. To understand and grasp the example we create a table 'stu' and 'stu1' that has the required fieldnames and datatypes respectively.

 

 

 

 

Create Table Stu:

Create table stu(id int, name varchar(10));

Create Table Stu1:

Create table stu1(id int, name varchar(10));

Insert values into stu:

The insert into add the records to the table 'stu' and 'stu1'.

insert into stu values (1,'komal');
insert into stu values (2,'ajay');
insert into stu values (3,'santosh');
insert into stu values (4,'rakesh');

Insert values into stu1:

insert into stu values (1,'komal');
insert into stu values (2,'ajay');
insert into stu values (3,'santosh');
insert into stu values (5,'tanuj');

Query for union: 

The Query Union is used to return the result of select queries from two table 'stu' and 'stu1'. The Union keyword returns in a distinct values by default.

SELECT * FROM stu
UNION
SELECT * FROM stu1;

Result

+------+---------+
| id   | name    |
+------+---------+
| 1    | komal   |
| 2    | ajay    |
| 3    | santosh |
| 4    | rakesh  |
| 5    | tanuj   |
+------+---------+