Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL row sort with NULL values and empty string at last

Tags:

postgresql

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; 
like image 221
user857574 Avatar asked Jul 22 '11 09:07

user857574


People also ask

Does Postgres treat empty string as NULL?

PostgreSQL databases treat empty strings and NULL as different.

How do I ORDER BY NULL last?

If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.

When data is sorted in ascending order NULL values appear first in the list?

SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.

Is empty string better than NULL?

However, it will throw an error of unique constraint if you use an empty string here. So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.


1 Answers

Use some conditional functions, e.g.

ORDER BY NULLIF(first_name, '') DESC NULLS LAST 
like image 193
kan Avatar answered Sep 18 '22 17:09

kan