Introduction
Here I will explain how to use order by in union query in sql server.
If you observe above query we are getting data from union statements as sub query and applying order by statement sub query to show the data in descending order.
Now we will see how to use order by clause with union statements in sql server with example.
If we execute above query we will get records in modifydate descending order.
Here I will explain how to use order by in union query in sql server.
- SELECT * FROM
- (
- Select Id as UserId, UserName as Name, RegisterDate From UserDetails
- Union
- select UserId, EmpName as Name, ModifyDate as RegisterDate From UserDetails
- ) smptbl
- ORDER BY RegisterDate DESC
- DECLARE @temp1 table(id int, name varchar(50),modifydate date)
- DECLARE @temp2 table(id int, name varchar(50),modifydate date)
- insert into @temp1(id,name,modifydate)
- values(1,'Sesu,Raj','2017-01-30'),
- (2,'Veera,Pandiayn','2016-02-10'),
- (3,'Soosai,Raj','2015-03-05')
- insert into @temp2(id,name,modifydate)
- values(13,'Honey','2017-04-15'),
- (21,'Imman,Alavala','2016-02-05'),
- (21,'Jai,Ganesh','2015-01-20')
- SELECT * FROM (
- Select id,name, modifydate from @temp1
- UNION
- Select id,name, modifydate from @temp2
- ) stbl ORDER BY modifydate DESC
Now we will see how to use order by clause with union statements in sql server with example.
If we execute above query we will get records in modifydate descending order.