Advertisement
jchaven

Add UUID field to MySQL

Nov 25th, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.70 KB | None | 0 0
  1. -- ----------------------------------------------------------
  2. -- ADDING TO DATABASE
  3. -- ----------------------------------------------------------
  4.  
  5. -- add UUID column
  6. ALTER TABLE test.tblapps DROP COLUMN uuid;
  7. ALTER TABLE test.tblapps ADD COLUMN uuid BINARY(16) AFTER fldAppID;
  8.  
  9. -- update new field with UUIDs generated by MySQL
  10. UPDATE test.tblapps set uuid = UNHEX(REPLACE(UUID(),'-',''));
  11.  
  12. -- insert record with known UUID
  13. INSERT INTO tblApps (uuid, fldName) VALUES (UNHEX('2F7D9DAC192C4867B83CEC97447C3FDA'),'Test 1');
  14.  
  15. -- select all rows (note UUID field is unreadable)
  16. SELECT * FROM tblapps;
  17.  
  18. -- select fields and HEX representation of UUID (UUID is readable)
  19. SELECT fldAppID, hex(uuid), fldName FROM tblapps;
  20.  
  21. -- compare UUID for known hex value. Note the "x" before the value!
  22. select fldAppID, fldName FROM tblapps where uuid = x'2F7D9DAC192C4867B83CEC97447C3FDA';
  23.  
  24. -- ----------------------------------------------------------
  25. -- MISCELLANEOUS
  26. -- ----------------------------------------------------------
  27.  
  28. -- examples of UUID funtion
  29. select uuid();
  30. select UNHEX(REPLACE(UUID(),'-',''));
  31.  
  32. -- create readable HEX value (you would never do this IRL)
  33. select hex( UNHEX(REPLACE(UUID(),'-','')) );
  34.  
  35. -- this "works" but, you cannot read it
  36. select UNHEX('2F7D9DAC192C4867B83CEC97447C3FDA');
  37. -- to make readable "hex it" (again never do this)
  38. select HEX(UNHEX('2F7D9DAC192C4867B83CEC97447C3FDA'));
  39.  
  40.  
  41. -- This will not work - too big with dashes
  42. UPDATE test.tblapps set uuid=UUID();
  43.  
  44.  
  45. -- using code (PHP) re-insert the dashes at the positions 9, 14, 19 and 24 to match your original UUID
  46. -- or leave as is (we really don't care about the dashes or what they represent - we just want unique
  47. -- values).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement