Skip to content

Instantly share code, notes, and snippets.

@pmn4
Last active October 12, 2020 13:15
Show Gist options
  • Save pmn4/00470c14675c98e438301a3475084fa6 to your computer and use it in GitHub Desktop.
Save pmn4/00470c14675c98e438301a3475084fa6 to your computer and use it in GitHub Desktop.
Create new Records with Unique Randomized Token using a Single Query
# Insert into table with a unique token column without a loop
# using `LEFT(UUID(), 8)` as the unique string generator for simplicity,
# feel free to use whatever method you'd like, including generating those
# in memory and putting raw strings into your query
INSERT INTO table(column1, column2, token_column)
SELECT "column1_value", "column2_value", token FROM (
# create a derived table containing five (feel free to increase)
# potential unique strings
SELECT LEFT(UUID(), 8) as token
UNION SELECT LEFT(UUID(), 8)
UNION SELECT LEFT(UUID(), 8)
UNION SELECT LEFT(UUID(), 8)
UNION SELECT LEFT(UUID(), 8)
) as tokens
WHERE NOT EXISTS (
SELECT 1
FROM table
WHERE token_column = tokens.token
)
LIMIT 1;
@pmn4
Copy link
Author

pmn4 commented Oct 12, 2020

you may need to convert the unique string, i.e.,

# SELECT LEFT(UUID(), 8)
SELECT CONVERT(LEFT(UUID(), 8) using latin1)

(assumes the token column is defined as latin1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment