View Full Version : order of results from a sql statement
heaps21
08-29-2004, 12:19 PM
Hi, I have an sql query which ends with "... AND id IN(" and then a list of id's in a specific order. When I run the query it doesnt return the results in the order that the id was specified. Is this normal or is there a way to ensure that the results will be returned in the order given in the "in" part of the sql statement?
thanks.
The In() just describes a collection of values.
To order the results, just add an " ORDER BY id ASC" to your query (behind the where-clause)
To get them in descending order:
ORDER BY id DESC
heaps21
08-29-2004, 04:31 PM
hmmm but I really need the results sorted into the same order as is in the "in" clause, not necessarily just ascending or descending, is this not possible then?
Thnks.
not with pure sql no. because the records are processed sequentialy. It's not as if the RDBM will run seperate selects for each value of the collection.
but you can do it inside your serverside language by dumpint the recordset in an array and then sort the array.
Alternatively, if it's consistently going to be sorted in the same order, then add a 'sort' field in the database. Put values in this field, and then sort on it.
You must know the order you want to sort in (or else you wouldn't know when it was wrong). The question is whether you put this in your database or in your application.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.