I have a question about mysql sorting. I have a database field with data like this 1,6,3,8,4
. I exploded this field value and made custom query for another table: WHERE id='1' or id='6' or id='3'...
.
It works fine BUT the result is ASC by id
. Is there a way to make the result appear at same order as the query?
By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
To sort by a column: Type: SELECT columns FROM table ORDER BY sort_column [ASC | DESC]; columns is one or more comma-separated column names, sort_column is the name of the column on which to sort the result, and table is the name of the table that contains columns and sort_column.
Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.
Use the FIELD()
function in the ORDER BY
clause:
ORDER BY FIElD(id, '1', '6', '3', ...);
See it in action here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With