Home >Database >Mysql Tutorial >How to Order PostgreSQL Records by Date with NULL Values First?

How to Order PostgreSQL Records by Date with NULL Values First?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-23 02:45:10274browse

How to Order PostgreSQL Records by Date with NULL Values First?

PostgreSQL database records are sorted by date, null values ​​first

In PostgreSQL, it is often necessary to sort query results in ascending order by a date/time field (e.g. last_updated) while ensuring that null value records come first.

PostgreSQL provides the ORDER BY modifier for NULLS FIRST | LAST expressions to achieve this purpose. By default, NULLS FIRST is used in descending order (DESC), causing null values ​​to be sorted last. To sort NULL values ​​first in ascending order (ASC), you can use the following syntax:

<code class="language-sql">... ORDER BY last_updated NULLS FIRST</code>

In order for the index to support this query, the index should match the sort order:

<code class="language-sql">CREATE INDEX foo_idx ON tbl (last_updated DESC NULLS LAST);</code>

PostgreSQL can handle inverted indexes efficiently, making it look like the following:

<code class="language-sql">CREATE INDEX foo_idx ON tbl (last_updated);</code>

However, for some query plans, the position of NULL values ​​can affect performance. For more information on this topic, please see the following:

The above is the detailed content of How to Order PostgreSQL Records by Date with NULL Values First?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn