简体   繁体   中英

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?

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.

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.

REPLACE语句执行相同的操作,如果不存在某行,则将其插入;如果存在,则将对其进行更新。

INSERT IGNORE在这里也很有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM