search

Home  >  Q&A  >  body text

How to sort SQL results if one column is empty?

I have questions about the sorting of query results. I have 3 columns that need to be sorted:

ORDER BY level DESC, logo DESC, bName ASC

I wanted to order the highest "level" via DESC first and this worked.

After that I want to order if "logo" is empty but not the logo content which my query executes.

Finally I want to order by bName ASC

So the output I want is this:

1. Level-3 has logo bName a-z
2. Level-3 has no Logo bName a-z
3. Level-2 has logo bName a-z
4. Level-2 has no Logo bName a-z
5. Level-1 has logo bName a-z
6. Level-1 has no Logo bName a-z

Is it possible to accomplish this with just one clean query?

Corresponding example input:

level LOGO bName
3 Test.jpg Test name
2 Test name
1 12test.jpg Another test name
1 3test.jpg anonymous
2 John Doe
2 Dodo
3 5test.jpg Test name
1 sdsd-test.jpg Test name

In some cases the column logo is empty (e.g. = '' ), but not NULL

P粉969666670P粉969666670261 days ago463

reply all(1)I'll reply

  • P粉745412116

    P粉7454121162024-04-05 22:01:17

    You haven't provided information about your data and what "logo is empty" actually means, but the principle is:

    ORDER BY 
      level DESC, 
      case when logo <> '' then 1 else 2 end,
      bName ASC;

    reply
    0
  • Cancelreply