I have a table that has a column (cat_name). Some are strings followed by numbers and others are just plain strings. I like to arrange it by putting all strings starting with 'Level' first.
Desired output:
I used this query
SELECT * FROM category ORDER BY
(CASE WHEN cat_name LIKE 'Level%' THEN 0
ELSE 1
END) ASC, cat_name
And got
And found this query here at stackoverflow for natural sorting
SELECT * FROM category WHERE cat_name LIKE 'Level%' ORDER BY LEFT(cat_name,LOCATE(' ',cat_name)), CAST(SUBSTRING(cat_name,LOCATE(' ',cat_name)+1) AS SIGNED), cat_name ASC
but I don't know how I can integrate it with my first query. The closest I could get is
SELECT * FROM category ORDER BY LEFT(cat_name,LOCATE(' ',cat_name)), CAST(SUBSTRING(cat_name,LOCATE(' ',cat_name)+1) AS SIGNED),
(CASE WHEN cat_name LIKE 'Level%' THEN 0
ELSE 1
END) ASC, cat_name ASC
But the strings with Levels is off. It is arranged numerically but they are not occupying the top position.
I think I am just missing something here. Hope someone can help me. Thanks in advance!
sqlfiddle: http://sqlfiddle.com/#!2/5a3eb/2
LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query. LIKE clause searches for a match between the patterns in a query with the pattern in the values present in an SQL table.
The SQL ORDER BY Keyword 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.
Try with:
SELECT * FROM category
ORDER BY (CASE WHEN cat_name LIKE 'Level%' THEN 0
ELSE 1
END)ASC,
LEFT(cat_name,LOCATE(' ',cat_name)), CAST(SUBSTRING(cat_name,LOCATE(' ',cat_name)+1) AS SIGNED),
cat_name ASC
It's to do with the order of statements within your ORDER BY
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