【发布时间】:2014-12-18 09:52:38
【问题描述】:
如何确定值得在sql 表上设置的索引?
以以下为例:
select *
from products
where name = 'car'
and type = 'vehicle'
and availability > 3
and insertion_date > '2015-10-10'
order by price asc
limit 1
想象一个有几百万个条目的数据库。
如果我为WHERE 和ORDER BY 子句中出现的所有属性的组合设置索引,会有好处吗?
例如:
create index i_my_idx on products
(name, type, availability, insertion_date, price)
【问题讨论】:
-
无法使用单个示例查询来确定正确的索引。您需要对所有个查询有一个概览,这些查询是最频繁和最重要的。它还取决于您的其余设置。有多少写操作(具体是什么)?数据分布、基数、资源等。你不能说“sql table”。 SQL 是查询语言,表就是表,如果你愿意的话,就是“数据库表”。
-
@a_horse_with_no_name:其实只要索引的所有列有相等条件,根本哪一列都没有关系先来。 See this related answer on DBA with a test case. 在这种情况下,我们有范围和平等。 Equality should go first. 所以显示的索引中列的顺序是好的。
-
@a_horse_with_no_name 感谢您提供详细的 cmets,我明白了。因此,让我们再举一个航班示例:可能最好为
departure_airport和arrival_airport添加索引。想象一下,我得到一个包含 1k 个条目的结果集。如果在departure_date上放置例如索引,会不会有更多好处,而在特定日期可能只有 10 个条目? -
有关基本经验法则,请阅读introduction in the manual 和this related answer。
标签: sql database postgresql