devxlogo

Sorting

Question:
I have a select query “Select * from Table where ID in (8, 2,3,78,32,1,7)” that I want returned in the same order that the IDs are in in the IN statement. By default SQL will return them sorted by the primary key (which is the ID). How can I do this?

Answer:
There is no easy way to specify your own order in the order clause. You would have to create another table with your values (8, 2,3,78,32,1,7) and their desired sequence and use that table in your select and order by. For example:

create table myorder( value int, sequence int)insert into myorder values (8,1)

etc..and then select …from …where id = myorder.valueorder by myorder.sequence

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.