ORDER BY clause behavior with NULL values

The way that different databases process the ORDER BY clause for tables with NULL values can vary depending on the database management system (DBMS) being used. However, there are some general rules that most databases follow when processing ORDER BY with NULL values:

By default, NULL values are treated as the lowest possible value in the ordering. This means that when you use ORDER BY to sort a table in ascending order, any rows with NULL values in the sorted column will appear at the beginning of the result set. Conversely, when sorting in descending order, any rows with NULL values will appear at the end of the result set.

Some databases provide options to change the default behavior when dealing with NULL values in the ORDER BY clause. For example, in Oracle, you can use the NULLS FIRST or NULLS LAST keywords to specify whether NULL values should appear first or last in the result set.

If you have multiple columns in your ORDER BY clause, the database will use the values in the first column to sort the rows. If two or more rows have the same value in the first column, the database will then use the values in the second column to sort those rows, and so on. If any of the columns being used for sorting contain NULL values, the same rules as above will apply.

MySQL SELECT 'x' FROM 'table_with_nulls'
ORDER BY 'x' IS NULL DESC,
         'x' DESC
MS SQL SELECT x FROM table_with_nulls
ORDER BY ( CASE
            WHEN x IS NULL THEN 0
            ELSE 1
           END ) ASC,
         x DESC
Oracle SELECT "x" FROM "table_with_nulls"
ORDER BY "x" DESC NULLS LAST

Комментарии

Популярные сообщения из этого блога

MapBox-compatible file formats and limitations