46°F

Aaron Parecki

  • Articles
  • Notes
  • Photos
  • Sorting a query in MySQL ignoring the word "The"

    April 19, 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)
    
    Sat, Apr 19, 2008 9:50pm -07:00 #code #database #MySQL #sorting #SQL
Posted in /articles

Hi, I'm Aaron Parecki, Director of Identity Standards at Okta, and co-founder of IndieWebCamp. I maintain oauth.net, write and consult about OAuth, and participate in the OAuth Working Group at the IETF. I also help people learn about video production and livestreaming. (detailed bio)

I've been tracking my location since 2008 and I wrote 100 songs in 100 days. I've spoken at conferences around the world about owning your data, OAuth, quantified self, and explained why R is a vowel. Read more.

  • Director of Identity Standards at Okta
  • IndieWebCamp Founder
  • OAuth WG Editor
  • OpenID Board Member

  • 🎥 YouTube Tutorials and Reviews
  • 🏠 We're building a triplex!
  • ⭐️ Life Stack
  • ⚙️ Home Automation
  • All
  • Articles
  • Bookmarks
  • Notes
  • Photos
  • Replies
  • Reviews
  • Trips
  • Videos
  • Contact
© 1999-2025 by Aaron Parecki. Powered by p3k. This site supports Webmention.
Except where otherwise noted, text content on this site is licensed under a Creative Commons Attribution 3.0 License.
IndieWebCamp Microformats Webmention W3C HTML5 Creative Commons
WeChat ID
aaronpk_tv