13

I have a table with 2 fields DATE and IMPORTANCE. Now I want to sort both these fields in DESCENDING ORDER so that the rows are ordered by IMPORTANCE for EACH DATE. For example, if sorted correct, rows should return like this:

Dec 3, 2010 - 10
Dec 3, 2010 - 10
Dec 3, 2010 - 8
Dec 3, 2010 - 7
Dec 3, 2010 - 3
Dec 3, 2010 - 1

Dec 2, 2010 - 10
Dec 2, 2010 - 9
Dec 2, 2010 - 3

Dec 1, 2010 - 8
Dec 1, 2010 - 5
Dec 1, 2010 - 5
Dec 1, 2010 - 4

Is there an efficient way of accomplishing this with only one query statement?

1
  • 4
    Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted. Commented Feb 26, 2019 at 15:36

2 Answers 2

35
SELECT * FROM yourtable
ORDER BY `DATE` DESC, `IMPORTANCE` DESC
Sign up to request clarification or add additional context in comments.

4 Comments

@Frank, DATE is a keyword, and in some cases, if you name a column with special words, your queries could have errors. ` escapes it.
No, DATE is not a keyword and ` isn't part of the ANSI SQL-standards. Use double quotes " to escape objectnames, MySQL also knows about double quotes, it's called ANSI_QUOTES. Check dev.mysql.com/doc/refman/5.5/en/reserved-words.html and dev.mysql.com/doc/refman/5.5/en/…
ANSI_QUOTES is not the standard behaviour of Mysql and enabling it alters the syntax needed to delimit literal strings, thus very likely breaking much of the software developed for Mysql.
@Frank in my own experience the backtick character does work as a quote marker for the field names in mysql which is handy when you have a field name that has a space in it. as: Select your name from yourtable doesn't work for me but Select `your name` from yourtable does.
7

You can add as many fields to ORDER BY as you want.

That'd be something like:

SELECT * FROM table ORDER BY `date` DESC, `importance` DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.