Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL ordering by text ASC, show numbers at last position

I have a SQL query and I need to order the result in ASC, but I need the numbers and spaces to be in the last position of the result, not first.

SELECT title FROM movie ORDER BY title ASC

Using the code above I get the titles starting from [space], 0-9, A,B,C... I need this form: A,B,C,...,Z,[anything else]

Thanks for any help.

like image 223
gustyaquino Avatar asked Jan 10 '11 14:01

gustyaquino


People also ask

Can we use numbers in ORDER BY clause?

We can use ROW_NUMBER to provide row number in a specified column based on Order By clause. In the following query, we want to get row number for SickLeaveHours column values in ascending order.

How do I ORDER BY ABC in SQL?

SQL Order by Alphabetical can be done on character-based column values using simply ORDER BY clause in ascending order. In SQL, various clauses can be used with the SELECT clause to achieve some specific functionality or make the resultset to be retrieved in a particular format.

Can we use ASC and DESC together in SQL?

If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.


2 Answers

ORDER BY CASE
           WHEN LOWER(LEFT(title, 1)) BETWEEN 'a' AND 'z' THEN 0
           ELSE 1
         END,
         title
like image 83
zerkms Avatar answered Oct 30 '22 18:10

zerkms


This is a bit of a hack, but it should work.

SELECT title FROM movie 
ORDER BY CASE WHEN title LIKE '[0-9]%' THEN 'ZZZ' + title ELSE title END ASC

The idea is to make your order clause transform the items starting with numbers by prepending them with ZZZ. As for the items starting with a space, you may just want to clean them up with LTRIM.

like image 40
Ben Hoffstein Avatar answered Oct 30 '22 17:10

Ben Hoffstein