22

Ok, I know I've done this before. But I cannot for the life of me figure it out. I created a table. One of the columns is labled "LogID", it is also the primary key.

How do I alter it so that this column generates a UUID for each new entry?

Thanks

Matt Winer
  • 395
  • 1
  • 3
  • 7

4 Answers4

23

Just create a trigger to run before insert to generate the UUID for the given column.

CREATE TRIGGER before_insert_mytable
  BEFORE INSERT ON mytable
  FOR EACH ROW
  SET new.LogID = uuid();
Jack Douglas
  • 40,517
  • 16
  • 106
  • 178
Robert Gabriel
  • 403
  • 4
  • 10
3

The UUID() expression generates a UUID when called.

Unfortunately (AFAIK anyway) MySQL won't allow expressions as a default value for a field. As a work around, you could always set the field to default null and have a trigger that updates the field with a UUID on insert.

ydaetskcoR
  • 330
  • 3
  • 12
2

I'm pretty sure you still can't, actually. I would seriously consider not using a UUID as a primary key, instead using a slimmer, nicer data type like INT. You can add your UUID as a separate column and update it via a TRIGGER, if that suits you.

Avarkx
  • 2,423
  • 13
  • 23
2

I just decided to include the UUID() command on the insert from my application.

Thanks all.

Matt Winer
  • 395
  • 1
  • 3
  • 7