In PostgreSQL, the ORDER BY clause allows us to sort the table’s data ascendingly or descendingly. A table can have non-null as well as null values. When it comes to NULL values, the ORDER BY clause treats them as the largest values. So, by default, the null values will be placed at the end/bottom of the table.
This blog will demonstrate the use of the ORDER BY clause with respect to null values.
How Does ORDER BY Clause Deal With the NULL Values in Postgres?
The ORDER BY clause treats the null entries as the largest values. So, when a table is sorted ascendingly, then the null values will come at the bottom of the table. On the other hand, when the table is sorted descendingly, the null values will be placed at the start of the table.
Example 1: ORDER BY Ascending
We will utilize the ORDER BY clause on the following “author_info” table:
SELECT * FROM author_info;
Let’s utilize the ORDER BY clause on the “author_exp” column of the given table:
SELECT * FROM author_info ORDER BY author_exp;
Null values are treated as the largest values by the ORDER BY clause.
Example 2: ORDER BY Descending
Let’s utilize the ORDER BY clause with the “author_exp” column of the “author_info” table. However, this time we will sort the “author_info” table descendingly:
SELECT * FROM author_info ORDER BY author_exp DESC;
This is how the ORDER BY clause works with the NULL values.
Conclusion
In PostgreSQL, the ORDER BY clause treats the null entries as the largest values. So, when a table is sorted ascendingly, then the null values will come at the bottom of the table. On the other hand, when the table is sorted descendingly, the null values will be placed at the start of the table. This write-up has demonstrated the usage of the ORDER BY clause with NULL values.