Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Friday, 22 April 2016

SQL Server Order By Union with Example

Introduction

Here I will explain how to use order by in union query in sql server.
  1. SELECT * FROM
  2. (
  3. Select Id as UserId, UserName as Name, RegisterDate From UserDetails
  4. Union
  5. select UserId, EmpName as Name, ModifyDate as RegisterDate From UserDetails
  6. ) smptbl
  7. ORDER BY RegisterDate DESC
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.

  1. DECLARE @temp1 table(id int, name varchar(50),modifydate date)
  2. DECLARE @temp2 table(id int, name varchar(50),modifydate date)
  3. insert into @temp1(id,name,modifydate)
  4. values(1,'Sesu,Raj','2017-01-30'),
  5. (2,'Veera,Pandiayn','2016-02-10'),
  6. (3,'Soosai,Raj','2015-03-05')
  7. insert into @temp2(id,name,modifydate)

  8. values(13,'Honey','2017-04-15'),
  9. (21,'Imman,Alavala','2016-02-05'),
  10. (21,'Jai,Ganesh','2015-01-20')
  11. SELECT * FROM (
  12. Select id,name, modifydate from @temp1
  13. UNION
  14. Select id,name, modifydate from @temp2
  15. ) 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.