索引是加速搜索引擎檢索數(shù)據(jù)的一種特殊表查詢。簡單地說,索引是一個(gè)指向表中數(shù)據(jù)的指針。一個(gè)數(shù)據(jù)庫中的索引與一本書的索引目錄是非常相似的。
拿漢語字典的目錄頁(索引)打比方,我們可以按拼音、筆畫、偏旁部首等排序的目錄(索引)快速查找到需要的字。
索引有助于加快 SELECT 查詢和 WHERE 子句,但它會(huì)減慢使用 UPDATE 和 INSERT 語句時(shí)的數(shù)據(jù)輸入。索引可以創(chuàng)建或刪除,但不會(huì)影響數(shù)據(jù)。
使用 CREATE INDEX 語句創(chuàng)建索引,它允許命名索引,指定表及要索引的一列或多列,并指示索引是升序排列還是降序排列。
索引也可以是唯一的,與 UNIQUE 約束類似,在列上或列組合上防止重復(fù)條目。
CREATE INDEX (創(chuàng)建索引)的語法如下:
CREATE INDEX index_name ON table_name;
單列索引
單列索引是一個(gè)只基于表的一個(gè)列上創(chuàng)建的索引,基本語法如下:
CREATE INDEX index_name ON table_name (column_name);
組合索引
組合索引是基于表的多列上創(chuàng)建的索引,基本語法如下:
CREATE INDEX index_name ON table_name (column1_name, column2_name);
不管是單列索引還是組合索引,該索引必須是在 WHEHE 子句的過濾條件中使用非常頻繁的列。
如果只有一列被使用到,就選擇單列索引,如果有多列就使用組合索引。
唯一索引
使用唯一索引不僅是為了性能,同時(shí)也為了數(shù)據(jù)的完整性。唯一索引不允許任何重復(fù)的值插入到表中?;菊Z法如下:
CREATE UNIQUE INDEX index_name on table_name (column_name);
局部索引
局部索引 是在表的子集上構(gòu)建的索引;子集由一個(gè)條件表達(dá)式上定義。索引只包含滿足條件的行?;A(chǔ)語法如下:
CREATE INDEX index_name on table_name (conditional_expression);
隱式索引
隱式索引 是在創(chuàng)建對象時(shí),由數(shù)據(jù)庫服務(wù)器自動(dòng)創(chuàng)建的索引。索引自動(dòng)創(chuàng)建為主鍵約束和唯一約束。
下面示例將在 COMPANY 表的 SALARY 列上創(chuàng)建索引:
# CREATE INDEX salary_index ON COMPANY (salary);
現(xiàn)在,用 \d company 命令列出 COMPANY 表的所有索引:
# \d company
得到的結(jié)果如下,company_pkey 是隱式索引 ,是表創(chuàng)建表時(shí)創(chuàng)建的:
nhooodb=# \d company Table "public.company" Column | Type | Collation | Nullable | Default ---------+---------------+-----------+----------+--------- id | integer | | not null | name | text | | not null | age | integer | | not null | address | character(50) | | | salary | real | | | Indexes: "company_pkey" PRIMARY KEY, btree (id) "salary_index" btree (salary)
你可以使用 \di 命令列出數(shù)據(jù)庫中所有索引:
nhooodb=# \di List of relations Schema | Name | Type | Owner | Table --------+-----------------+-------+----------+------------ public | company_pkey | index | postgres | company public | department_pkey | index | postgres | department public | salary_index | index | postgres | company (3 rows)
一個(gè)索引可以使用 PostgreSQL 的 DROP 命令刪除。
DROP INDEX index_name;
您可以使用下面的語句來刪除之前創(chuàng)建的索引:
# DROP INDEX salary_index;
刪除后,可以看到 salary_index 已經(jīng)在索引的列表中被刪除:
nhooodb=# \di List of relations Schema | Name | Type | Owner | Table --------+-----------------+-------+----------+------------ public | company_pkey | index | postgres | company public | department_pkey | index | postgres | department (2 rows)
雖然索引的目的在于提高數(shù)據(jù)庫的性能,但這里有幾個(gè)情況需要避免使用索引。
使用索引時(shí),需要考慮下列準(zhǔn)則:
索引不應(yīng)該使用在較小的表上。
索引不應(yīng)該使用在有頻繁的大批量的更新或插入操作的表上。
索引不應(yīng)該使用在含有大量的 NULL 值的列上。
索引不應(yīng)該使用在頻繁操作的列上。