I want a column to default to a GUID, so if I am doing an insert and I don't explicitly set the value, I want it to default to a new GUID value.
how can I do this?
I want a column to default to a GUID, so if I am doing an insert and I don't explicitly set the value, I want it to default to a new GUID value.
how can I do this?
Being that UUID() isn't accepted as a DEFAULT constraint, you need to use a trigger.
This one sets the value for the
NEW_TABLE.uuid
column:Previous answer is not quite right - you've got to be careful with triggers... they will actually overwrite any default value you pass in if used as in that example. Everything will work fine when the primary key is not set, but if you pass one in with the INSERT it will get wiped with a new random one by the trigger.
For it to work properly you must check whether the field already has a value before assigning a new one, as follows:
I use
ASCII()
to check the new field value, asASCII()
will return 0 for an empty string whether the data is in textual or binary format (and an empty string is the default value for fields with no default set). I also use binary(16) to store my UUID's for most efficient storage space and query speed... if you don't want to deal with the complexities of binary fields then you can simply useUUID()
in place ofUNHEX(REPLACE(UUID(),'-',''))
with a char(36) field.