Shadi Almosri
Shadi Almosri

Reputation: 11989

Update first then Insert if row doesn't exist (SQL) Rather than check if row exists first?

I've always used the method of checking a table to see if a row exists, and then update it with my new data or insert it if it doesn't exist, but it's got me thinking what would be wrong with simply doing an update, if no rows are affected, then do an insert statement, that could potentially speed up my script and put less load on the server.

Anyone foresee any problems with this?

Upvotes: 1

Views: 1704

Answers (4)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29995

INSERT IGNORE is also useful here.

Upvotes: 0

yann.kmm
yann.kmm

Reputation: 837

the REPLACE statement does the same thing, if a row doesn't exist it will insert it, if it exists it will update it.

Upvotes: 1

Etienne Dechamps
Etienne Dechamps

Reputation: 25341

What's wrong with REPLACE?

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.

Upvotes: 3

Pascal MARTIN
Pascal MARTIN

Reputation: 401062

If by "see if a row exists" you mean by primary key, you might be interested by 12.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax :

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:

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;

Maybe you can use this ?

Compared to what you said, tt's doing exactly the other way arround : trying to insert, and if there is a DUPLICATE KEY error, it updates the line... But it allows you not to check if the line exists first.

Still, it only works by primary key / unique index ; not with any kind of where clause.

Upvotes: 2

Related Questions