Joe Half Face
Joe Half Face

Reputation: 2323

Can I apply something like `NULLS LAST` but without sorting by that column values that are not null?

Imagine I have query

 SELECT  "somethings.* 
 FROM "somethings" 
 ORDER BY description DESC NULLS LAST, popularity DESC`

It will sort first on description, put all rows with null description at the end, and then apply popularity sort.

But what I want is just to put rows with null description last, not to sort results primary on description string, and then sort results on popularity.

Ideally I want to achieve it in one query.

Upvotes: 1

Views: 103

Answers (2)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You can use is null in order by clause :

order by (case when description is null 
               then 1 else 0 end), description desc, popularity desc;   

Upvotes: 4

Haleemur Ali
Haleemur Ali

Reputation: 28233

slighly shorter solution

ORDER BY description IS NOT NULL, description, popularity DESC

This works because True > False

Upvotes: 3

Related Questions