Improving OFFSET performance in PostgreSQL

后端 未结 5 825
失恋的感觉
失恋的感觉 2021-01-29 20:46

I have a table I\'m doing an ORDER BY on before a LIMIT and OFFSET in order to paginate.

Adding an index on the ORDER BY column makes a massive difference to performance

5条回答
  •  长情又很酷
    2021-01-29 21:17

    I don't know anything about "counted b-tree indexes", but one thing we've done in our application to help with this is break our queries into two, possibly using a sub-query. My apologies for wasting your time if you're already doing this.

    SELECT *
    FROM massive_table
    WHERE id IN (
        SELECT id
        FROM massive_table
        WHERE ...
        LIMIT 50
        OFFSET 500000
    );
    

    The advantage here is that, while it still has to calculate the proper ordering of everything, it doesn't order the entire row--only the id column.

提交回复
热议问题