I know how to sort a result set:
SELECT * FROM `People` ORDER BY `LastName` ASC
However, the results that have an empty LastName show at the beginning. How do I sort in ascending order, and show the NULL results at the end instead of the beginning?
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
SQL treats NULL values to be less than 0 so while sorting in ascending order, NULL values always appear to be at first.
SQLite. In contrast to PostgreSQL and Oracle, SQLite treats NULLs as very small values and puts them first in an ascending sort and last in a descending sort. Starting with SQLite version 3.30. 0, this behavior can also be easily changed using the NULLS FIRST / NULLS LAST option.
If the null ordering is not specified then the handling of the null values is: - NULLS LAST if the sort is ASC - NULLS FIRST if the sort is DESC - If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with ...
SELECT
*
FROM
People
ORDER BY
CASE WHEN LastName IS NULL THEN 1 ELSE 0 END,
LastName
You could also simply use
SELECT
*
FROM
People
ORDER BY
COALESCE(LastName, 'ZZZZZ')
Technically, the second version would fail if a person actually had a LastName in your DB of "ZZZZZZ".
NOTE: I'm sure it's just because you're giving an example, but I hope you're not using SELECT * in actual production code... :)
SELECT *, LastName IS NULL AS nullity
FROM `People`
ORDER BY nullity ASC, `LastName` ASC
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