I am trying to script some test data for my application. The table I am trying to populate has a column of type string that holds a UUID. I need to write an insert statement that populates this column.
My current statement almost works, but it generates the same ID for all inserts. The generated column does not have to be a true UUID but does need to be unique in the table.
A simplified version of my statement looks like this:
SELECT
null as id,
whi.externalId,
(select lower(hex( randomblob(4)) || '-' || hex( randomblob(2))
|| '-' || '4' || substr( hex( randomblob(2)), 2) || '-'
|| substr('AB89', 1 + (abs(random()) % 4) , 1) ||
substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))) as GUID
FROM WorkHerdInventories as whi
This results in the following:
Probably SQLite tries to optimize the code so it executes the subquery only once and returns the same UUID
for all rows.
Remove that SELECT
statement that you use to get the UUID
(you don't need it anyway):
SELECT
null id,
externalId,
lower(
hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' ||
substr(hex( randomblob(2)), 2) || '-' ||
substr('AB89', 1 + (abs(random()) % 4) , 1) ||
substr(hex(randomblob(2)), 2) || '-' ||
hex(randomblob(6))
) GUID
FROM WorkHerdInventories
See the demo.
Results:
id | externalId | GUID
---- | ---------- | ------------------------------------
null | 78 | 55ad2d25-12b7-4a29-b538-41384cc25b84
null | 79 | d9f49c6a-7627-4e75-a494-987434dea7a2
null | 80 | f87feaa3-2dad-43fd-97e5-77353b289799
null | 81 | ff9557e9-3ab4-4423-b92d-e6c0b92620f7
null | 82 | 4558a483-bd25-45c9-8ffa-eae8168fc8fb
null | 83 | 9491bbcd-311d-4c64-8418-da522f9201a6
null | 84 | 8ac52122-b9ae-40fb-b4c6-7c83238ae8d5