I am having a difficult time forming a conditional INSERT
I have x_table with columns (instance, user, item) where instance ID is unique. I want to insert a new row only if the user already does not have a given item.
For example trying to insert instance=919191 user=123 item=456
Insert into x_table (instance, user, item) values (919191, 123, 456)
ONLY IF there are no rows where user=123 and item=456
Any help or guidance in the right direction would be much appreciated.
In case you don't want to set a unique constraint, this works like a charm :
Hope it helps !
So this one stands for PostgreSQL
What you want is
INSERT INTO table (...) SELECT ... WHERE ...
. from MySQL 5.6 manual.In you case it's:
Or maybe since you're not using any complicated logic to determiante whether to run the
INSERT
or not you could just set aUNIQUE
key on the combination of these two columns and then useINSERT IGNORE
.If you add a constraint that (x_table.user, x_table.item) is unique, then inserting another row with the same user and item will fail.
eg:
Although it's good to check for duplication before inserting your data I suggest that you put a unique constraint/index on your columns so that no duplicate data can be inserted by mistake.
If your DBMS does not impose limitations on which table you select from when you execute an insert, try:
In this,
dual
is a table with one row only (found originally in Oracle, now elsewhere too). The logic is that the SELECT statement generates a single row of data with the required values, but only when the values are not already found.Alternatively, look at the MERGE statement.