Composite key autoincrements

Warning: This blogpost has been posted over two years ago. That is a long time in development-world! The story here may not be relevant, complete or secure. Code might not be complete or obsoleted, and even my current vision might have (completely) changed on the subject. So please do read further, but use it with caution.
Posted on 17 Dec 2010
Tagged with: [ autoincrement ]  [ MySQL

Autoincrement is sometimes called a “poor-man-sequence”. Sequences in other DB systems are counters that can be used for automatically number fields when inserting data, just like autoincrement in MySQL does, but they can be much more complex. However, in MySQL you do not always you want or need increments of 1. Sometimes you need something a little more complex than that and MySQL leaves you pretty much in the cold.  There is a neat little trick that can solve some “autoincrement” problems…

The “trick”

It is not so much a trick as it is a poorly documented feature. Suppose you need data like this:

item        subitem
    1            1
    1            2
    1            3
    2            1
    2            2
    3            1

You want to autoincrement the subitem field, but as soon as you insert an new item, it has to start again with 1. What you can do is create a composite primary key from the item and subitem fields. Then you add the autoincrement value to the subitem field. This will automatically number your subitems correctly.

  `item` int(11) unsigned NOT NULL,
  `subitem` int(11) unsigned NOT NULL auto_increment,
  `name` varchar(100) character set ascii NOT NULL,
  PRIMARY KEY  (`item`,`subitem`)

The major drawback though is that it can only be used with MyISAM tables. InnoDB does not support this kind of autoincrements so you have to rely on triggers / Stored procedures again.