I am running a insert statement to insert data, but I want to check for any duplicate entries based on date and then do an entry.
All I want is if today a user enters product_name='x', ‘x’ is unique so that no one can enter product name x again today. But of course the next day they can.
I do not want to run a select before the insert to do the checking. Is there an alternative?
You can use the mysql
insert into... on duplicate updatesyntax which will basically enter in a new row if one isn’t there, or if the new row would have caused a key constraint to kick in, then it can be used to update instead.Lets say you have the following table:
And ID is set as the primary key in the database (meaning it CANNOT have two rows with the same value in it) you would normally try to insert like this:
But this would generate an error as there is already a row with ID of 1 in it.
By using the
insert on duplicate updatethe query now looks like this:Now, rather than returning an error, it updates the row with the new name instead.
Edit: You can add a unique index across two columns with the following syntax:
This will now let you use the syntax above to insert rows while having the same ID as other rows, but only if the name is different – or in your case, add the constraint on the varchar and date fields.
Lastly, please do add this sort of information into your question to start with, would have saved everyone a bit of time 🙂