Home >Database >Mysql Tutorial >How to Sort Data in PostgreSQL with NULLs First in Ascending Order?
NULL value first ascending sort in PostgreSQL
When sorting in ascending order in a PostgreSQL table, you usually want to prioritize records containing NULL values over records with non-NULL values. This is particularly important when dealing with date/time fields that allow empty or NULL input.
PostgreSQL provides the convenient ORDER BY
modifier in the NULLS FIRST
statement to solve this problem. Using this modifier ensures that records with NULL values appear before records with non-NULL values in an ascending sort operation.
Here is a sample query:
<code class="language-sql">ORDER BY last_updated ASC -- NULL 值的 last_updated 记录排在最后?</code>
You can add the NULLS FIRST
modifier to this query to get the desired results:
<code class="language-sql">ORDER BY last_updated ASC NULLS FIRST</code>
It should be noted that PostgreSQL also provides the NULLS LAST
modifier. This modifier does the opposite; it ensures that NULL-valued records appear after non-NULL-valued records in an ascending sort.
NULLS FIRST
and NULLS LAST
modifiers can significantly increase the flexibility and control of PostgreSQL sort operations. They enable users to handle NULL values in a way that suits their specific requirements, ensuring that non-NULL values appear after or before NULL values in an ascending sort, as appropriate.
The above is the detailed content of How to Sort Data in PostgreSQL with NULLs First in Ascending Order?. For more information, please follow other related articles on the PHP Chinese website!