开发者

What is the performance hit of this order_by django query?

MyModel.objects.all().order_by('-timestamp')

There is a unique key on timestamp and another column:

`code` varchar(3) NOT NULL,
`timestamp` date NOT NULL,
 UNIQUE KEY `exchangerate_currency_70883b95_uniq` (`code开发者_高级运维`,`timestamp`)

All I want is to obtain the latest row in the table. The query achieves that but I am thinking of the future when it will grow to 100K rows. Are there glaring performance problems with this query & schema ?


Without seeing your full query, and your schema, it's impossible to do more than speculate.

But... I believe the order of columns in a multi-column index in MySQL is important. This would mean that your index on (code,timestamp) is likely unusable for ordering by timestamp. If you changed the order to instead be (timestamp,code), it probably would be useable for ORDER BY timestamp, however it may hurt performance for other queries.

If your usage requires an index for both, you may need to create a second index on just the timestamp column.


Since your query is on code and timestamp, the index can't be used if there is no code in the WHERE clause (and you'll see filesort in the results of explain). if there is code= condition, the query will be fast enough. However, if you have 100000+ records that match the query part and you want to order by timestamp, it will be extremly fast if you limit the timestamp to let's say last several days (you have to choose the limit based on your application).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜