- 要使用 primary key 的話,建議要使用 non-clustered primary key。不要用 MySQL 的預設設置的 clustered primary key 。否則會得到 clustered index penalty 。
- 效能的重點在 index-only scan
由於網站上的文章也相當多,我讀了兩三篇之後,改變心意,用速成的方式來學好了。於是我做了網站上的習題。結果,五題裡頭,我還真的只會兩題,就是有讀過網站上文章所以才會寫兩題。 題目很有啟發性,下方就是其中的一題,題目是不好的 SQL 語句,要能夠看出效能的瓶頸才算通過。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE INDEX tbl_idx ON tbl (date_column); | |
SELECT text, date_column | |
FROM tbl | |
WHERE YEAR(date_column) = '2012'; | |
# It should changes to the below: | |
# Wrapping the table column in a function renders the index useless for this query. | |
# Write queries for continuous periods as explicit range condition: | |
SELECT text, date_column | |
FROM tbl | |
WHERE date_column >= STR_TO_DATE('2012-01-01', '%Y-%m-%d') | |
AND date_column < STR_TO_DATE('2013-01-01', '%Y-%m-%d'); |