weblab-tw / ddia-study-group

Designing Data-Intensive Applications Study Group
36 stars 4 forks source link

第三章節:clustered index vs non clustered index 的差異?- Nissen #41

Open nissenyeh opened 2 years ago

nissenyeh commented 2 years ago

clustered index vs non clustered index 的差異?

問題

  1. 關於 clustered index vs non clustered index ,我目前我的理解如下,不知道是否正確?

    • clustered index: 實體的資料(physical data)的「排序方式」,因為實體資料一定只會有「一種」排序,所以clustered index 只會有一種。例子:設定 Primary key 後,實體資料的排序就會按照 Primary key 的順序。
    • non clustered index: 除實體資料,額外建立 index table,排序後單純用 pointer 去指到實體的資料(physical data),因為這種index table 可以創很多,所以 non clustered index 可以有很多。
  2. 有沒有可能,有些資料庫的 Primary key 是 clustered index,但有些資料庫的 Primary key 是 non clustered index?

  3. clustered index vs non clustered index 跟 primary index vs secondary index 的關係?( Clustered index 必然是 primary index,而 non clustered index 必然是 secondary index 嗎?)

Reference

  1. 文章說明

在某些情況下,從索引到堆文件的額外跳躍對讀取來說性能損失太大,因此可能希望將被索引的行直接存儲在索引中。 這被稱為聚集索引(clustered index)。 例如,在 MySQL 的 InnoDB 儲存引擎中,表的主鍵總是一個聚集索引,次級索引則引用主鍵(而不是堆檔中的位置)【31】。 在 SQL Server 中,可以為每個表指定一個聚集索引【32】。

在聚集索引(在索引中存儲所有的行數據)和 非聚集索引(僅在索引中存儲對數據的引用)之間的折衷被稱為 覆蓋索引(covering index) 或 包含列的索引(index with included columns),其在索引內存儲表的一部分列【33】。 這允許通過單獨使用索引來處理一些查詢(這種情況下,可以說索引 覆蓋(cover) 了查詢)【32】。

  1. 參考文章
nissenyeh commented 2 years ago

有沒有可能,有些資料庫的 Primary key 是 clustered index,但有些資料庫的 Primary key 是 non clustered index?

針對這題,查到該篇文章,根據這篇文章

看起來 Primary key 可以是 clustered index 也可以是 non clustered index,只是前者比較常見

Here is the common misconception prevailing in the industry. Primary Key has to be Clustered Index

In reality the statement should be corrected as follows: Primary Key can be Clustered or Non-clustered but it is a common best practice to create a Primary Key as Clustered Index.