R
R
Roman Kitaev2016-01-04 13:44:38
PostgreSQL
Roman Kitaev, 2016-01-04 13:44:38

Why doesn't sorting on multiple fields use indexes?

Good afternoon. The problem arose very strange and, in my opinion, illogical.
I have some table tbl with fields id, count and something else.
id - primary key, index created on count (btree)
So, I need to sort by count desc, then by id asc. Well, I make this request:

select * from tbl order by count desc, id limit 10;

It all terribly lags, and explain issues Seq Scan.
Well, ok, I'm trying to sort only by the first field: The index is used. Okay, on another field: The index is being used again. Okay, armed with crutches, I make the following request:
select * from tbl order by count desc limit 10;
select * from tbl order by id limit 10;
select * from (
    select * from tbl order by count desc limit 10;
) as a order by id;

Voila! Index is in use! The results are identical, of course.
But I have a Django ORM and I want to use a normal notation, not a crutch with SQL:
Entry.objects.order_by('-count', 'pk')[:10]
Has anyone encountered this problem or is it my hook hands?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
romy4, 2016-01-04
@deliro

The engine can only use one index at a time. Think.

V
Vladimir, 2016-01-04
@vintello

here the author writes well

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question