Posts Tagged sorting
Sorting a query in MySQL ignoring the word “The”
Posted by aaron in Website Development on April 19th, 2008
When you have a database of books or movies, some of the titles begin with “The.” If you do a regular ORDER BY on the table, all the titles that start with “the” get clumped together. One option is running an unsorted query and sorting in PHP, but it would be better to sort at the database level. Here is a query I came up with to do that, using an IF function in MySQL!
SELECT * FROM movies ORDER BY IF(SUBSTRING(title,1,4)="The ",SUBSTRING(title,5),name)
Now create a custom function for that, and it’s even easier to use!
CREATE FUNCTION SORTNAME (name VARCHAR(255)) RETURNS VARCHAR(255) RETURN IF( (LCASE(SUBSTRING(name,1,4)) = 'the '), SUBSTRING(name,5), name );
Now you can use it in a query like this:
SELECT * FROM movies ORDER BY SORTNAME(title)