mysql keep position of query with union statement – mysql

1. select something, date_something from my_table
where [conditions]
union
2. select something, date_something from my_table
where [conditions]
union
3. select something, date_something from my_table
where [conditions]

This pseudo-code at least in my workbench returns me the exact result I need. I didn’t use the ORDER BY keyword at the end, which I always do, because applying will destroy the order obviously.

Is there a way to assure the query would return data in the following order? For me it is really important I could fix the order by 1,2,3 “partitions”, rather than applying it overvalues. I hope you understand.

Any ideas would be welcomed.

Answer

You should be able to add a field to do that, e.g.:

select 1 as Partition, something, date_something 
from my_table 
where [conditions] 
union 
select 2 as Partition, something, date_something 
from my_table 
where [conditions] 
union 
select 3 as Partition, something, date_something 
from my_table 
where [conditions] 
order by Partition

Leave a Reply

Your email address will not be published. Required fields are marked *