When should I use primary key or index?

后端 未结 6 1772
感动是毒
感动是毒 2020-12-04 11:12

When should I use a primary key or an index?

What are their differences and which is the best?

6条回答
  •  遥遥无期
    2020-12-04 11:50

    The primary key is by definition unique: it identifies each individual row. You always want a primary key on your table, since it's the only way to identify rows.

    An index is basically a dictionary for a field or set of fields. When you ask the database to find the record where some field is equal to some specific value, it can look in the dictionary (index) to find the right rows. This is very fast, because just like a dictionary, the entries are sorted in the index allowing for a binary search. Without the index, the database has to read each row in the table and check the value.

    You generally want to add an index to each column you need to filter on. If you search on a specific combination of columns, you can create a single index containing all of those columns. If you do so, the same index can be used to search for any prefix of the list of columns in your index. Put simply (if a bit inaccurately), the dictionary holds entries consisting of the concatenation of the values used in the columns, in the specified order, so the database can look for entries which start with a specific value and still use efficient binary search for this.

    For example, if you have an index on the columns (A, B, C), this index can be used even if you only filter on A, because that is the first column in the index. Similarly, it can be used if you filter on both A and B. It cannot, however, be used if you only filter on B or C, because they are not a prefix in the list of columns - you need another index to accomodate that.

    A primary key also serves as an index, so you don't need to add an index convering the same columns as your primary key.

提交回复
热议问题