MySQL and AUTO_INCREMENT

So, MySQL has this lovely feature – you can have a column which will default to the next integer value when you insert some data. You don’t need to set it, it just takes the next value itself.

Unsurprising, the column that is auto incrementing has to be part of a PRIMARY KEY. I mean, that’s what makes the auto increment useful.

However, sometimes I find it can be necessary to have the auto incrementing column as a secondary column in a composite Primary Key. For example, if I have two columns, ‘msg’ and ‘thread’ that are the Primary Key, and I run:

Insert into myTable (thread, text ) values ( 1, 'Andy' );
Insert into myTable (thread, text ) values ( 2, 'Fred' );

Three times, then I would expect to see:

| thread | msg | Text |
-----------------------
|    1   |  1  | Andy |
|    1   |  2  | Andy |
|    1   |  3  | Andy |
|    2   |  1  | Fred |
|    2   |  2  | Fred |
|    2   |  3  | Fred |

What I was getting recently was different. First, I couldn’t have a secondary column in a primary key that was auto incrementing. Odd, I was sure I’d done it that way before. So I tried using a separate key for my composite. That worked, but the data I was getting now was:

| thread | msg | Text |
-----------------------
|    1   |  1  | Andy |
|    1   |  3  | Andy |
|    1   |  5  | Andy |
|    2   |  2  | Fred |
|    2   |  4  | Fred |
|    2   |  6  | Fred |

Not what I wanted. Anyway, to cut a long story short, I figured out the problem – table engines. When I’d build composite primary keys using auto increment, it was on a MyISAM table type (or table engine, as I believe the new parlance is). I’ve now got the latest version of MySQL, and it seems to be defaulting to INNODB table engines. INNODB, while adding cool stuff like transaction support, won’t allow auto increment on a secondary column in a primary key.

So, there you go, hopefully someone will find that a useful thing to know. Just change your table type, and that’ll fix it.

Advertisements
MySQL and AUTO_INCREMENT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s