Sorting MySQL rows using column values


Posted in: mysql | Save to del.icio.us | Twit This! 25 Jul 2008

In MySQL it is easy to sort rows by using the ORDER BY clause on the column name. Recently on a client request the sort had to be done using the column values rather than the name. Since I had never come across sorting using values, a couple of minutes of searching was in order; You can do the ordering by using the ‘field’ function like in the below example.

The first and second parameters for the field function are the column name and value respectively. If you want more than 1 value to sort by you need to add the remaining afer the second parameter like this.

...field( column_name, value1, value2, value3...)

For example:

...ORDER BY field(status, 'For Lease', 'Rent', 'Purchase') desc

Example sorting using the column names.

SELECT *
FROM property_master pm,prop_details_master pdm
WHERE pdm.property_id = pm.property_id
AND pm.active = 1
ORDER BY status desc

Example sorting using column values.

select *
FROM property_master pm,prop_details_master pdm
WHERE pdm.property_id = pm.property_id
AND pm.active = 1
ORDER BY field(status, 'For Lease') desc



Share this post

Share on Facebook
Share on Twitter
Share on StumbleUpon
Share on Delicious
Share on Digg
Share on Technorati
Share on Reddit
Feeds RSS Subscribe to site Feed

Other related posts



Comment Form

Use the html <code> tag to insert small source code snippets

For longer code examples use http://pastie.org/.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

Recent Comments

  • sameer: You can try this in your templates header.php : http://pastie.org/867569 [...]
  • avanthi: I played it back by using selenium RC [...]
  • avanthi: Ohh, ok no problem, here the actual issue is with IE, when i play back in firefox it is working fine [...]
  • Veerendra: Hi sameer great plugin to filter content. I was searching this kind of filtering plugin for doing [...]
  • sameer: My apologies! I'm not conversant with SharePoint. [...]
  • avanthi: Is it possible to automate share point people picker control through selenium. When i record throug [...]
  • sameer: Check to see if the 'IDE > options > format' is set to HTML. [...]
  • sameer: Google strips any newline characters form the text. Although it does accept it with the online trans [...]

  • Users Online

    • 6 Users Online
    • 5 Guests, 1 Bot