It is quite OK to have a composite PRIMARY KEY
, whether or not one of the columns is AUTO_INCREMENT
. In fact, there is a good use case for doing such.
Here's the use case:
- The table is large (bigger than
innodb_buffer_pool_size
-- hence random fetches might require disk I/O)
- The application queries tend to fetch several of the rows for a given "user_id". (Example: The table is a list of purchases made by users.)
- The rows for a given user will come in sporadically over time. (Hence, the rows for a user are rarely located 'together.)
- InnoDB orders the table by the
PRIMARY KEY
. (fact)
- Disk I/O, when needed, is likely to be the slowest part of the query. (fact)
If an auto_inc were used as the PK, the rows for a given user would be scattered around the table. This would make the query slower, possibly even requiring multiple disk fetches.
If, instead, the rows for a user were "clustered" together by having the PRIMARY KEY
start with user_id
, then all the rows for that user might be in a single (or very few) block, thereby making disk caching more effective.
In this example, the following is advised:
id ... AUTO_INCREMENT,
user_id ...,
...
PRIMARY KEY(user_id, id), -- provides the clustering
INDEX(id) -- This is necessary and sufficient to keep auto_inc happy.
Your 4-column PK is not any different.