PostgreSQL: speed up SELECT query in table with millions of rows

后端 未结 3 1886
不思量自难忘°
不思量自难忘° 2020-12-30 16:49

I have a table with > 4.5 million rows and my SELECT query is far too slow for my needs.

The table is created with:

CREATE TABLE all_leg         


        
3条回答
  •  半阙折子戏
    2020-12-30 17:15

    The index won't help.

    Two solutions:

    1. You chould either change the query to:

      WHERE dep_dt >= '2017-08-15 00:00:00' AND dep_dt < '2017-08-16 00:00:00'
      

      Then the index can be used.

    2. Create an index on an expression:

      CREATE INDEX ON all_legs(((dep_dt AT TIME ZONE 'UTC')::date));
      

      (or a different time zone) and change the query to

      WHERE (dep_dt AT TIME ZONE 'UTC')::date = '2017-08-16'
      

      The AT TIME ZONE is necessary because otherwise the result of the cast would depend on your current TimeZone setting.

    The first solution is simpler, but the second has the advantage that you can add price_ct to the index like this:

    CREATE INDEX ON all_legs(((dep_dt AT TIME ZONE 'UTC')::date), price_ct);
    

    Then you don't need a sort any more, and your query will be as fast as it can theoretically get.

提交回复
热议问题