Which record caused INSERT IGNORE not to insert? - mysql

In MySQL, when an INSERT IGNORE does not insert anything, is it possible to get the row that caused INSERT IGNORE to "fail"?

Another and more correct approach is to use LAST_INSERT_ID() in ON DUPLICATE KEY UPDATE
That is to change:
INSERT IGNORE INTO the_table (id) VALUES (1);
To:
INSERT INTO the_table (id) VALUES (1)
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id);
This wil make no changes to the table, but the following call to LAST_INSERT_ID() will return either the id of the newly inserted item or the last result explicitly passed to the function.

One way you can achieve this is to add a field which you can use as a flag, and then add ON DUPLICATE KEY UPDATE dup = dup+1 (or similar) to your query.

Related

IF NOT EXISTS then INSERT

I'm trying to add a value to a table but not without checking if the value already exists. This is what I have so far:
IF NOT EXISTS (
SELECT series.seriesName
FROM series
WHERE series.seriesName='Avengers'
)
BEGIN
INSERT INTO series (seriesName) VALUES 'Avengers'
END;
Database is a MySQL db on Ubuntu
You can use IGNORE keyword here.
It could look like:
INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'
The important thing is to create a unique key on seriesName field as it seems that you want it to be unique.
INSERT IGNORE doesn't make the insert when key value already exists.
If you would like to be able to get id (primary key value) for row that wasn't inserted (already existed), you can do the following trick:
INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'
ON DUPLICATE KEY UPDATE seriesID= LAST_INSERT_ID(seriesID)
Then you will be able to get the ID with LAST_INSERT_ID() function no matter if the row was inserted or not.

INSERT if PRIMARY KEY is not present, IGNORE if present [duplicate]

This is what I'm doing right now (name is UNIQUE):
SELECT * FROM fruits WHERE name='apple';
Check if the query returned any
result. If yes, don't do anything. If
no, a new value has to be inserted:
INSERT INTO fruits (name) VALUES ('apple');
Instead of the above is it ok to insert the value into the table without checking if it already exists? If the name already exists in the table, an error will be thrown and if it doesn't, a new record will be inserted.
Right now I am having to insert 500 records in a for loop, which results in 1000 queries. Will it be ok to skip the "already-exists" check?
You can use the IGNORE feature:
INSERT IGNORE INTO fruits VALUES ('apple')
If there is a key violation, it just skips this value
check out
INSERT IGNORE INTO ...
and
INSERT ON DUPLICATE KEY UPDATE ...
Thes second method is preferred as the IGNORE statement simply causes mysql to issue warning instead of error

Getting last insert id for mysql after Insert

I have a query like so:
INSERT INTO table1 (field1,field2) VALUES ('$value1','$value2') ON DUPLICATE KEY UPDATE field1 = '$value1'
I then want to get the last insert id if it does the insert, how can I do this? If the query ends up doing an update I dont want the last insert id. Is there a way to determine if it did an update or a insert?
I guess I should of searched the site before posting. Basically adding this worked:
id=LAST_INSERT_ID(id)
On the on duplicate update. I found that answer here:
Duplicate Key Last Insert ID
According to this MySQL Manual Page:
If a table contains an AUTO_INCREMENT
column and INSERT ... ON DUPLICATE KEY
UPDATE inserts or updates a row, the
LAST_INSERT_ID() function returns the
AUTO_INCREMENT value.

UPDATE record if present; else INSERT

I want to update a record which may or may not be present in a table. If it is not present in the database then it will be inserted.
To prevent from select I am using UPDATE statement first and checking affected_rows > 0 if not then I am inserting this record into the table.
I was wondering if there is a better way to do this?
You could use INSERT ... ON DUPLICATE KEY UPDATE syntax:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
The difference between this and REPLACE (Femaref's answer) is that REPLACE will delete the old row and then insert a new row if a key is duplicated, while this will update the existing row.
Use Replace instead of Insert.
http://dev.mysql.com/doc/refman/5.0/en/replace.html

How to INSERT a record or UPDATE if it already exists?

I have a table with columns record_id (auto inc), sender, sent_time and status.
In case there isn't any record of a particular sender, for example "sender1", I have to INSERT a new record otherwise I have to UPDATE the existing record which belongs to "user1".
So if there isn't any record already stored, I would execute
# record_id is AUTO_INCREMENT field
INSERT INTO messages (sender, sent_time, status)
VALUES (#sender, time, #status)
Otherwise I would execute UPDATE statement.
Anyway.. does anyone know how to combine these two statements in order to insert a new record if there isn't any record where the field sender value is "user1" otherwise update the existing record?
MySQL supports the insert-on-duplicate syntax, f.e.:
INSERT INTO table (key,col1) VALUES (1,2)
ON DUPLICATE KEY UPDATE col1 = 2;
If you have solid constraints on the table, then you can also use the REPLACE INTO for that. Here's a cite from MySQL:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
The syntax is basically the same as INSERT INTO, just replace INSERT by REPLACE.
INSERT INTO messages (sender, sent_time, status) VALUES (#sender, time, #status)
would then be
REPLACE INTO messages (sender, sent_time, status) VALUES (#sender, time, #status)
Note that this is a MySQL-specific command which doesn't occur in other DB's, so keep portability in mind.
As others have mentioned, you should use "insert...on duplicate key update", sometimes referred to as an "upsert". However, in your specific case you don't want to use a static value in the update, but rather the values you pass in to the values clause of the insert statement.
Specifically, I think you want to update two columns if the row already exists:
1) sent_time
2) status
In order to do this, you would use an "upsert" statement like this (using your example):
INSERT INTO messages (sender, sent_time, status)
VALUES (#sender, time, #status)
ON DUPLICATE KEY UPDATE
sent_time = values(sent_time),
status = values(status);
Check out "Insert on Duplicate Key Update".
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
One options is using on duplicate update syntax
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Other options is doing select to figure out if record exists and then doind inser/update accordingly. Mind that if you're withing transaction select will not explicitly terminate the transaction so it's safe using it.
use merge statement :
merge into T1
using T2
on (T1.ID = T2.ID)
when matched
then update set
T1.Name = T2.Name
when not matched
then insert values (T2.ID,T2.Name);