0

Example of what I have:

SELECT [thing] FROM [A]
UNION ALL
SELECT [thing] FROM [B]
UNION ALL
SELECT [thing] FROM [C]
UNION ALL
SELECT [thing] FROM [D]
UNION ALL 
SELECT [thing] FROM [E]

In my union I want thing to be sorted by oldest to newest entry date. So, if I add a value to my thing field from table A today I want to see that value get sorted to the bottom of my column in my union query. Is there a way to do this by using Order By?

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Krista
  • 261
  • 1
  • 5
  • it depends on whether you are maintaining an `entry_date` column of some sort in all the tables that are part of your query. If you don't have that column defined, then no, you can't. – sstan Oct 07 '15 at 01:44

1 Answers1

0

select the date column from the tables in union all and use it to order the thing column. This is because you can't use order by when using union. It can only be specified at the end of all queries.

select thing from
(
SELECT [thing],[datecolumn] as dt FROM [A]
UNION ALL
SELECT [thing],[datecolumn] FROM [B]
UNION ALL
SELECT [thing],[datecolumn] FROM [C]
UNION ALL
SELECT [thing],[datecolumn] FROM [D]
UNION ALL 
SELECT [thing],[datecolumn] FROM [E]
) t
order by dt 
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
  • I am sorry for bothering you, but can you take a look at a similar question i have? http://stackoverflow.com/questions/41303336/select-top-with-multiple-union-and-with-order-by – Dillinger Dec 23 '16 at 15:49