2

My table contains history of values relating to objects, it looks like:

create table History (
    object_id  bigint  NOT NULL,
    value      int     NOT NULL,
    date       bigint  NOT NULL
);

How can I index it to optimize following query:

select * from History
    where object_id = ? and date < ?
    order by date desc
    limit ?

1 Answer 1

3

Create composite index object_id + date

CREATE INDEX object_id_date ON History(object_id, `date`);
Sign up to request clarification or add additional context in comments.

8 Comments

@pst: nope, with conditions like key_part1 = const AND key_part2 < const the only order that makes sense is key_part1 + key_part2, as long as range condition prevents of further using of right index part. In this particular case oid + date covers both WHERE condition and ORDER BY (bacause of left-most part is constant)
thanks, does it optimize all 4 parts of my query? is any of them left unoptimized which i should find another way to optimize it?
@JohnS: It optimizes WHERE and ORDER BY. Not sure what other 2 parts you're talking about. LIMIT - cannot be optimized, it is just limit. And SELECT * is not optimized - because it is * there
thanks, just another naive question: do you think this is an optimized structure to store and query history of values in a RDB when there are too many objects and history records? any better design pattern you know about?
@JohnS Is there a reason to do otherwise [now or in the immediate future]? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.