Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve the order of a SQL query using the IN command

Tags:

People also ask

Does SQL preserve order?

It will keep the same sort order with SQL query code. If there is order by defined, it will keep the same sort order too.

Can we use order by in insert?

The only thing that order by on an insert is guaranteed to do is assign the values of an identity column if one exists. Your select has no order by, hence SQL is in no way required to return the data in any particular order.

How do I order chronologically in SQL?

Use the ORDER BY keyword and the name of the column by which you want to sort. This way, you'll sort the data in ascending order by this column. You could also use the ASC keyword to make it clear that the order is ascending (the earliest date is shown first, the latest date is shown last, etc.).

Is order by always last in SQL?

It depends on the user that, whether to order them in ascending or descending order. The default order is ascending. The SQL ORDER BY clause is used with the SQL SELECT statement. Note: SQL ORDER BY clause always come at the end of a SELECT statement.


SELECT * FROM tblItems
WHERE itemId IN (9,1,4)

Returns in the order that SQL finds them in (which happens to be 1, 4, 9) however, I want them returned in the order that I specified in the array.

I know I could reorder them after in my native language (obj c), but is there a neat way to do this in SQL?

Somthing like this would be great:

ORDER BY itemId (9,1,4) --    <-- this dosn't work :)