Jimski
Jimski

Reputation: 944

Postgresql order by first column, but with nulls or zeros in second column last

How to sort a table with multiple columns where sort is alphabetic by first column but all the alphabetic entries that have nulls or zeros in the second column appear last.

Before sort Table "user"

username    monies    zip
jim         25       87888
allan       12       34333
adrian       0       97677
abel       null      87888
will         4       88788

After the sort Table "user"

username    monies    zip
allan       12       34333
jim         25       87888
will         4       88788
abel       null      87888
adrian       0       97677

I tried this but it doesn't work

 SELECT 
     * 
 FROM 
     "user"
 ORDER BY 
     name ASC, 
     monies nulls last

Upvotes: 1

Views: 1559

Answers (1)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

Just do the sorting for 0 or null first and then do the alphabetic sort by username

order by case when monies = 0  or monies is null then 1 else 0 end,  username

Upvotes: 2

Related Questions