Search code examples
sqlmysqlguiddefaultuuid

Default value of GUID for MySQL column


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?


Solution

  • 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:

    delimiter $$
    
    CREATE
    DEFINER=`root`@`localhost`
    TRIGGER `example`.`newid`
    BEFORE INSERT ON `example`.`new_table`
    FOR EACH ROW
    BEGIN
      SET NEW.`uuid` = UUID();
    END
    $$