質問

I'm using will_paginate to get the top 10-20 rows from a table, but I've found that the simple query it produces is scanning the entire table.

sqlite> explain query plan 
SELECT "deals".* FROM "deals" ORDER BY created_at DESC LIMIT 10 OFFSET 0;
0|0|0|SCAN TABLE deals (~1000000 rows)
0|0|0|USE TEMP B-TREE FOR ORDER BY

If I was using a WITH clause and indexes, I'm sure it would be different, but this is just displaying the newest posts on the top page of the site. I did find a post or two on here that suggested adding indexes anyway, but I don't see how it can help with the table scan.

sqlite> explain query plan 
SELECT deals.id FROM deals ORDER BY id DESC LIMIT 10 OFFSET 0;
0|0|0|SCAN TABLE deals USING INTEGER PRIMARY KEY (~1000000 rows)

It seems like a common use case, so how is it typically done efficiently?

役に立ちましたか?

解決

The ORDER BY created_at DESC requires the database to search for the largest values in the entire table.

To speed up this search, you would need an index on the created_at column.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top