Skip to content

Instantly share code, notes, and snippets.

@mattvryan
Created October 15, 2014 17:23
Show Gist options
  • Save mattvryan/4aab858722f0910e737f to your computer and use it in GitHub Desktop.
Save mattvryan/4aab858722f0910e737f to your computer and use it in GitHub Desktop.
MySQL "INSERT ... WHERE NOT EXISTS" if you don't have/know a primary/unique key
INSERT INTO my_table (unique_but_non_indexed_col1, col2, col3)
SELECT * FROM (SELECT 'unique_val1', 'val2', 'val3') AS tmp
WHERE NOT EXISTS (
SELECT id FROM my_table WHERE unique_but_non_indexed_col1='unique_val1'
) LIMIT 1;
@mattvryan
Copy link
Author

Probably not very performant, but useful for run-rarely scripts

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