Should we include sort column, primary key on composite index (MySQL)

前端 未结 1 721
醉话见心
醉话见心 2021-01-19 04:01

Table (Simplified):

+---------------------------------------------------------------------+
| id (Primary AI) |  user_id  |  status  |  type  |   data   |   i         


        
相关标签:
1条回答
  • 2021-01-19 04:55

    Answer depends on engine you use:

    • MyISAM - adding id to index can and probably will help
    • InnoDB - Primary Key is already part of each secondary index, because innodb stores rows in BTREE sorted by primary key and index needs primary to point to actual row - in that case adding it is redundant if it is last in the index (but doing so won't add it twice, so it should not make things worse). In some cases you may want to add it as not-last, or you have multicolumn primary and you add some columns to your index in different order - there should be no problem with it, innodb will append remaining columns of primary to that index, but can use those added before without duplicating them)

    So answers:

    1. In InnoDB it is unnecessary, In MyISAM it is good in case you actually use that sorting, if you dont use it, adding it only makes that index bigger.
    2. Order of columns in the table definition and order in index are separate things, so it is OK
    3. Yes, that index seems really good - but you can check yourself using EXPLAIN, there is possibility of even better performance - "covering index", but that comes with a cost so unless the query is critical and underperforming, it is probably overkill.
    0 讨论(0)
提交回复
热议问题