views:

32

answers:

4

if I have the following result sets:

id, name 
1, The Popper
2, Brittany
3, Fledgler
4, The Nightingale

How do I sort them by name so that it disregards the "The" word and sorts the as follows:

id, name
1, Britanny
2, Fledler
3, The Nightingale
4, The Popper

Thanks in advance. I am using MySQL

+1  A: 
 SELECT id,title,
    CASE WHEN LOWER(SUBSTRING_INDEX(Title, ' ', 1))
            IN ('a', 'an', 'the')
        THEN CONCAT(
            SUBSTRING(Title, INSTR(Title, ' ') + 1),
            ', ',
            SUBSTRING_INDEX(Title, ' ', 1)
        )
        ELSE Title
    END AS TitleSort
FROM books
ORDER BY TitleSort
lock
+3  A: 

Try:

SELECT id, name
FROM myTable
ORDER BY TRIM(LEADING 'The ' FROM name)

More info here.

eumiro
+1; it's worth mentioning that this will be slow on huge data sets, as it probably won't be able to use indexes.
Pekka
A: 

Use this --> http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim to remove the "The" from the beginning of the keyword in the Order by clause.

joni
+1  A: 

There are several answers that suggest "live" trimming, which will work fine.

However, if performance is important (huge lots of rows) consider having a separate column title_sort that contains the title with The and other disregarded words already removed.

That way, the database engine can make full use of indexing and other optimizations.

Pekka