Skip to content
Advertisement

Default sort my own order without sort by

Select id from MyTable where id in (28,5,7,35)

I want to leave the order as is in the in Clause, however SQL output is ordered by ID

I know how to achieve the result using a temp table. Is there a better way to do it?

Advertisement

Answer

Not sure what you mean by I know how to achieve the result using a temp table as you haven’t shown this, however you could insert your values into a temp table / table variable with an Identity in the order you require the results, then inner join. This is likely the most performant option for larger result sets.

Note that if you want a result set in a specific order, you must specify an order by clause.

declare @filter table(seq int identity(1,1), id int)
insert into @filter values (28),(7),(5),(35)

select * 
from TheTable t
join @filter f on f.id = t.id
order by f.seq;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement