user857574
user857574

Reputation: 861

PostgreSQL row sort with NULL values and empty string at last

I have used the following SQL, and it's working fine, but I need to sort empty strings also. Please give me guidance on this.

SELECT id, first_name, last_name 
FROM users
ORDER BY first_name DESC NULLS LAST
limit 10;

Upvotes: 33

Views: 11365

Answers (2)

Piyush Chaudhary
Piyush Chaudhary

Reputation: 313

ORDER BY IF( first_name = '' OR first_name IS NULL,1,0), first_name;

Upvotes: 1

kan
kan

Reputation: 28991

Use some conditional functions, e.g.

ORDER BY NULLIF(first_name, '') DESC NULLS LAST

Upvotes: 47

Related Questions