You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

InnoDB表二级索引值相同时是否会按主键排序?

Answer

Yes, when secondary index values in an InnoDB table are identical, the corresponding index entries will be sorted by the table's primary key.

Why this happens:

InnoDB secondary indexes are structured such that each index entry includes not only the secondary key columns but also the table's primary key columns. Since the primary key is unique, this ensures every secondary index entry is uniquely identifiable—even when the secondary key values are the same. As a result, when multiple entries share the same secondary key value, they are ordered by their primary key values to maintain a consistent, sorted structure within the index.

Reference from MySQL Documentation:

InnoDB sorts secondary index records by the primary key if the secondary key columns are equal.

Example Illustration:

Suppose you have a table products defined as:

CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT,
    category VARCHAR(50),
    name VARCHAR(100)
);
CREATE INDEX idx_category ON products(category);

If you insert multiple rows with the same category value (e.g., 'electronics'), the idx_category index will store these entries sorted first by category, then by the primary key id. When querying with WHERE category = 'electronics', the database can retrieve the rows in primary key order directly from the secondary index without additional sorting.

内容的提问来源于stack exchange,提问作者chi tian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:44:52