索引不是“加上就会更快”的通用优化开关,它本质上是额外维护的一份有序数据结构:查询受益,写入和存储付费。

原文链接

我的结论

关键信息

文章把几个常见误区拆得很清楚。

第一,索引之所以能避免 full table scan,本质上依赖的是类似 binary search 的有序结构,所以它不是“免费加速”,而是一笔用空间和写入成本换读取性能的交易。

第二,复合索引不是字段集合,而是有顺序的数据结构。它会先按第一个字段排序,再在组内按第二个字段排序,所以查询条件和排序方式如果不符合这个前缀顺序,索引就可能帮不上忙。

第三,函数会改变索引匹配条件。索引建在 name 上,并不等于 lower(name) 也能命中;如果查询里用了表达式,就要考虑 functional index。

第四,索引的设计应该跟查询选择性一起考虑。像 “legendary = true” 这种只覆盖少量记录的条件,更适合 partial index;而如果查询所需列已经都在索引里,就能用 covering index,避免回表再取其他列。

摘录

Reads get faster, writes get slower.

indexes are real data structures and we must store them.

Composite indexes care about order

The index is on name, not lower(name).

Now the index has just 80 entries instead of 1000.

Everything the query needs is already in the index.

我的补充

ref