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;
PostgreSQL databases treat empty strings and NULL as different.
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.
SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.
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.
Use some conditional functions, e.g.
ORDER BY NULLIF(first_name, '') DESC NULLS LAST
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With