Home » MySQL

MySQL – Case insensitive ORDER BY

3 March 2010 3 Comments

MySQL by default will make the ORDER BY option in queries case sensitive. This means that rows with the same starting letters (but different case) may be ordered non-alphabetically. There are three solutions to this. One is to force all database entries to be forced to upper-case or lower-case when inserting. Another is to use the collate option. The other solution is to change the query itself.

Option 2 (Thanks to eremit)
mysql_query(“SELECT * FROM names ORDER BY name COLLATE ‘latin1_general_ci’);

See: MySQL Reference – Case Sensitivity in String Searches and MySQL Reference – Character Set Support

Option 3:

The MySQL query for case insensitive ORDER BY is to add the LOWER() to your field name. For instance:

mysql_query(“SELECT * FROM names ORDER BY lastname”);

will be: mysql_query(“SELECT * FROM names ORDER BY LOWER(lastname)“);

3 Comments »

  • eremit said:

    Generally that’s worth a try, but as far as I remember accents might be still a problem.

    Another solution to get an case-insensitive ORDER BY is:

    mysql_query(“SELECT * FROM names ORDER BY name COLLATE ‘latin1_general_ci’);

    See: MySQL Reference – Case Sensitivity in String Searches and MySQL Reference – Character Set Support

  • admin (author) said:

    Thanks for bringing up the point about the accents. The COLLATE ‘latin1_general_ci’ is a much better solution. I’ll update the post with your helpful tip.

  • işitme cihazı said:

    very nice blog :)

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.