Aram Arabyan
Aram Arabyan

Reputation: 2359

Should I include Order "by column" to index?

I have a query

select * from cp where customer_Id = ? order by date_created desc limit 1

I like to optimize execution of this query bu creating index for customer_Id column.

Question: should my index contain date_created column also ?

Upvotes: 0

Views: 48

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

In general, yes. If you can, include it as a descending column:

create index idx_cp_customerId_datecreated cp(customer_id, date_created desc)

Do note however:

  • Some databases do not actually implement the desc option on indexes.
  • Some databases will not use an ascending index for a descending sort
  • This index will be no worse (for your query) than if you leave out date_created.

Upvotes: 1

Related Questions