Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show each table after the other in UNION SQL

I want to show two result sets in one result set, using UNION

The problem is, I want it to show all of the first table’s records, and then go to the next one

But since SQL Server automatically orders the results by the first column, the final results get ordered by ID column, which both tables have

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now, there is a record in [table 1] with the ID value of "1", and there is also a record in [table 2] with the ID value of "1"

Same goes for ID value being 2, 3, 4 ,5 …

Now, SQL Server orders all the final records by ID, and therefore, it is shown like this:

[table 1].[record 1]
[table 2].[record 1]
[table 1].[record 2]
[table 2].[record 2]

I want it to be like this:

[table 1].[record 1]
[table 1].[record 2]
[table 1].[record 3]

and so on, until all the [table 1]’s records are displayed, and then go to [table 2]’s records

[table 2].[record 1]
[table 2].[record 2]
[table 2].[record 3]

>Solution :

Add an "ordering column" e.g.

select 0 Orderb, T1.*
from Table1 T1

union all

select 1 Orderb, T2.*
from Table2 T2

order by OrderBy, id; -- whatever columns you wish to order by
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading