[Solved] How to create an index properly for DESC NULLS LAST sorting
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

How to create an index properly for DESC NULLS LAST sorting

Database type:

I created an index without specifying ordering or nulls first/last e.g.:

CREATE INDEX index_name ON TABLE table_name (date)

and now my ORDER BY DESC NULLS LAST queries run extremely slowly.

I read in PostgreSQL documentation, that

NULLS FIRST Specifies that nulls sort before non-nulls. This is the default when DESC is specified.

NULLS LAST Specifies that nulls sort after non-nulls. This is the default when DESC is not specified.

therefore if I create an index like this (for col date):

CREATE INDEX index_name ON TABLE table_name (date DESC NULLS LAST)

will I get a serious performance gain for queries like

SELECT * FROM table_name ORDER BY date DESC NULLS LAST LIMIT 50 OFFSET 0

?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid OFFSET In LIMIT Clause (query line: 6): OFFSET clauses can be very slow when used with high offsets (e.g. with high page numbers when implementing paging). Instead, use the following \u003ca target\u003d"_blank" href\u003d"http://www.eversql.com/faster-pagination-in-mysql-why-order-by-with-limit-and-offset-is-slow/"\u003eseek method\u003c/a\u003e, which provides better and more stable response rates.
  2. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  3. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX table_name_idx_date ON "table_name" ("date" desc);
The optimized query:
SELECT
        * 
    FROM
        table_name 
    ORDER BY
        table_name.date DESC NULLS LAST LIMIT 50 OFFSET 0

Related Articles



* original question posted on StackOverflow here.