joeware - never stop exploring... :)

Information about joeware mixed with wild and crazy opinions...

Using GUIDs/UUIDs for Primary Key of MariaDB or MySQL DB Table

by @ 10:41 am on 5/24/2015. Tags:
Filed under db

I am posting this so I can find it again, if others find it useful that is good too.

Define Primary Key as CHAR(36) NOT NULL DEFAULT ‘0’

Define a trigger

CREATE DEFINER=`root`@`localhost` TRIGGER `<TableName>_CreateUUIDPrimaryKey` BEFORE INSERT ON `<TableName>` FOR EACH ROW BEGIN
  set NEW.<PrimaryKeyFieldName> = UUID();
END

 

Example:

CREATE TABLE `TestTable` (
    `ID` CHAR(36) NOT NULL DEFAULT ‘0’,
    `Name` CHAR(50) NOT NULL,
    PRIMARY KEY (`ID`)
)
COLLATE=’latin1_swedish_ci’
ENGINE=InnoDB
;

CREATE DEFINER=`root`@`localhost` TRIGGER `TestTable_CreateUUIDKey` BEFORE INSERT ON `TestTable` FOR EACH ROW BEGIN
  set NEW.ID = UUID();
END

Rating 3.00 out of 5

Comments are closed.

[joeware – never stop exploring… :) is proudly powered by WordPress.]