Indexing on a field and “order by” on another field

六月ゝ 毕业季﹏ 提交于 2020-01-02 15:08:16

问题


Let's assume I have a small database with three columns : "id1", "id2" and "date". I am indexing my database on the field "id1" since it is a frequently selected field (many select queries are ran with ex: where "id1" = 125548).

In some particular query I have, I need to sort the records of a user based on the date" field in the table which is not indexed. My curiosity is if the sort operation (which is basically a order-by operation) on the date field will be ran on the whole database or only on the rows of the user (ex: 125548) which I select based on the "id1" field.

Below is an example query:

SELECT u 
FROM UserView u 
WHERE u.viewedId=:viewedId AND u.viewDate >=:dateLimit 
ORDER BY u.viewDate DESC

回答1:


FIrst, you can create an index that will do both, assuming your query really is simple:

select . . 
from table t
where id1 = X
order by col2

A composite index on table(id1, col2) can be used for both the where and order by.

As for your question. In general, the filtering will be done first. There may be some databases that would look at the statistics for the table and say "gosh, half the records have id1 and I have an index on col2 -- I'll use the index for the sort". However, no database would sort all the data (as opposed to using an index) and then filter it afterwards. Sorts are more efficient on smaller amounts of data.

EDIT:

For your query:

SELECT u 
FROM UserView u 
WHERE u.viewedId=:viewedId AND u.viewDate >=:dateLimit 
ORDER BY u.viewDate DESC;

The optimal index is UserView(ViewId, viewDate). Assuming that UserView is a table (or perhaps a view that only selects from one table), then this index should be used for both the WHERE (both clauses) and the ORDER BY.



来源:https://stackoverflow.com/questions/29256984/indexing-on-a-field-and-order-by-on-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!