SQL Indexing and Tuning e-Book for developers: Use The Index, Luke covers Oracle, MySQL, PostgreSQL, SQL Server, ...

索引的本质是一种排好序的数据结构,类似字典里的目录

索引要解决的根本问题是,提供一种有序的数据,这样查找起来更快

不加索引,需要在查询的时候从表的首行开始遍历比对,表量级大的时候次数多

加了索引,MySQL 内部维护一个数据结构,如红黑树(右子树的元素大于根节点,左子树的元素小于根节点)建立索引,能大大减少 IO

创建索引时,你需要确保该索引是应用在 SQL 查询语句的条件(一般作为 WHERE 子句的条件)。实际上,索引也是一张表,该表保存了主键与索引字段,并指向实体表的记录。

CREATE INDEX indexName ON table_name (column_name)

修改表结构添加索引

ALTER table tableName ADD INDEX indexName(columnName)

创建表时指定

CREATE TABLE mytable(
	ID INT NOT NULL,
	username VARCHAR(16) NOT NULL,
	INDEX [indexName] (username(length))
);

删除索引

DROP INDEX [indexName] ON mytable;

唯一索引 其索引列的值必须唯一,如果是串联(组合)索引,则列值的组合必须唯一

CREATE UNIQUE INDEX indexName ON mytable(username(length))

A database index is more complex than a printed directory because it undergoes constant change. An SQL database must process insert, delete and update statements immediately, keeping the index order without moving large amounts of data.

The database combines two data structures to meet the challenge: a doubly linked list and a search tree. These two structures explain most of the database's performance characteristics.

The Leaf Nodes

The primary purpose of an index is to provide an ordered representation of the indexed data. It's not possible to store the data sequentially because of insert statements. The solution to the problem is to establish a logical order that is independent of physical order in memory.

The logical order is established via a double linked list. Every node has links to two neighboring entries, very much like a chain.