PHP Order By Multiple Fields in MySQL

Want to be able to order by two or more database fields / columns using the ASC and DESC order clause

You can sort query results in ascending or descending order on one or more of the columns in the result set by using the ASC or DESC keywords with the ORDER BY clause.

Ordering By Two Fields

SELECT * FROM table ORDER BY (field1 / field2) DESC

Ordering By Three Fields

If both field1 and field2 match in more then one row, then use a third to order them by:

SELECT * FROM table ORDER BY (field1 / field2) DESC, field3 DESC

You may also like...

11 Responses

  1. the One says:

    This is a cool explanation… i was looking for that. Thanks

  2. thomas says:

    this was great! thanks!

  3. rv says:

    great answer – thanks!

  4. rv says:

    Actually the above code did not work for me. This does:

    ORDER BY FIELD1,FIELD2 ASC

    (or DESC, etc)

  5. Amandeep says:

    Thanks Alot dear

    Its really working

  6. anyone says:

    Thanks man I love you 🙂

  7. iim.hlk says:

    thx for the info, but in my case the solution was the use of GREATEST(fieldA,fieldB) as XXX order by XXX…

    i learn it oN this posT ::

    http://teethgrinder.co.uk/perm.php?a=MySQL-max-of-two-columns

    pD :: i hope be useful 😉

  8. Vinnymen says:

    You are a lifesaver 😀

  9. dollardyne says:

    What exactly does ORDER BY (field1 / field2) DESC mean as I don’t get the same result as
    ORDER BY field1 DESC, field2 DESC (which is correct)…

    I interpret the 1st statement as
    order by (the result of field1 DIVIDED BY field2) DESC because / is the division operator.

    If this is the case this is only applicable on numeric columns and again not so reliable
    field1 field2 result
    5 10 5/10 = 0.5
    4 2 4/2 = 2

    so the 4 would be above the 5

Leave a Reply