How to INSERT If Row Does Not Exist (UPSERT) in MySQL

MySQL provides a number of useful statements when it is necessary to INSERT rows after determining whether that row is, in fact, new or already exists.

Below we’ll examine the three different methods and explain the pros and cons of each in turn so you have a firm grasp on how to configure your own statements when providing new or potentially existing data for INSERTION.

Using INSERT IGNORE

Using INSERT IGNORE effectively causes MySQL to ignore execution errors while attempting to perform INSERT statements. This means that an INSERT IGNORE statement which contains a duplicate value in a UNIQUE index or PRIMARY KEY field does not produce an error, but will instead simply ignore that particular INSERT command entirely. The obvious purpose is to execute a large number of INSERT statements for a combination of data that is both already existing in the database as well as new data coming into the system.

For example, our books table might contain a few records already:

mysql> SELECT * FROM books LIMIT 3;
+----+-------------------------+---------------------+----------------+
| id | title                   | author              | year_published |
+----+-------------------------+---------------------+----------------+
|  1 | In Search of Lost Time  | Marcel Proust       |           1913 |
|  2 | Ulysses                 | James Joyce         |           1922 |
|  3 | Don Quixote             | Miguel de Cervantes |           1605 |
+----+-------------------------+---------------------+----------------+
3 rows in set (0.00 sec)

If we have a large batch of new and existing data to INSERT and part of that data contains a matching value for the id field (which is a UNIQUE PRIMARY_KEY in the table), using a basic INSERT will produce an expected error:

mysql> INSERT INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

On the other hand, if we use INSERT IGNORE, the duplication attempt is ignored and no resulting errors occur:

mysql> INSERT IGNORE INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
Query OK, 0 rows affected (0.00 sec)

Using REPLACE

In the event that you wish to actually replace rows where INSERT commands would produce errors due to duplicate UNIQUE or PRIMARY KEY values as outlined above, one option is to opt for the REPLACE statement.

When issuing a REPLACE statement, there are two possible outcomes for each issued command:

  • No existing data row is found with matching values and thus a standard INSERT statement is performed.
  • A matching data row is found, causing that existing row to be deleted with the standard DELETE statement, then a normal INSERT is performed afterward.

For example, we can use REPLACE to swap out our existing record of id = 1 of In Search of Lost Time by Marcel Proust with Green Eggs and Ham by Dr. Seuss:

mysql> REPLACE INTO books
    (id, title, author, year_published)
VALUES
    (1, 'Green Eggs and Ham', 'Dr. Seuss', 1960);
Query OK, 2 rows affected (0.00 sec)

Notice that even though we only altered one row, the result indicates that two rows were affected because we actually DELETED the existing row then INSERTED the new row to replace it.

More information on using REPLACE can be found in the official documentation.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Using INSERT ... ON DUPLICATE KEY UPDATE

The alternative (and generally preferred) method for INSERTING into rows that may contain duplicate UNIQUE or PRIMARY KEY values is to use the INSERT ... ON DUPLICATE KEY UPDATE statement and clause.

Unlike REPLACE – an inherently destructive command due to the DELETE commands it performs when necessary – using INSERT ... ON DUPLICATE KEY UPDATE is non-destructive, in that it will only ever issue INSERT or UPDATE statements, but never DELETE.

For example, we have decided we wish to replace our id = 1 record of Green Eggs and Ham and revert it back to the original In Search of Lost Time record instead. We can therefore take our original INSERT statement and add the new ON DUPLICATE KEY UPDATE clause:

mysql> SET @id = 1,
    @title = 'In Search of Lost Time',
    @author = 'Marcel Proust',
    @year_published = 1913;
INSERT INTO books
    (id, title, author, year_published)
VALUES
    (@id, @title, @author, @year_published)
ON DUPLICATE KEY UPDATE
    title = @title,
    author = @author,
    year_published = @year_published;

Notice that we’re using normal UPDATE syntax (but excluding the unnecessary table name and SET keyword), and only assigning the non-UNIQUE values. Also, although unnecessary for the ON DUPLICATE KEY UPDATE method to function properly, we’ve also opted to utilize user variables so we don’t need to specify the actual values we want to INSERT or UPDATE more than once.

As a result, our id = 1 record was properly UPDATED as expected:

mysql> SELECT * FROM books LIMIT 1;
+----+------------------------+---------------+----------------+
| id | title                  | author        | year_published |
+----+------------------------+---------------+----------------+
|  1 | In Search of Lost Time | Marcel Proust |           1913 |
+----+------------------------+---------------+----------------+
1 row in set (0.00 sec)

 

[출처] https://chartio.com/resources/tutorials/how-to-insert-if-row-does-not-exist-upsert-in-mysql/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 25085
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 24564
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 25943
525 데이터 사이언스 학습 안내 졸리운_곰 2018.11.11 165
524 MySQL 중복 데이터 찾아서 삭제하기 졸리운_곰 2018.10.29 141
523 MySQL에서 중복되는 행을 하나만 남기도 모두 삭제하는 방법 졸리운_곰 2018.10.29 94
522 데이터베이스 진단의 핵심기법 file 졸리운_곰 2018.09.11 145
521 kor-char-rnn-tensorflow 한글텍스트 RNN 학습 텐서플로우 file 졸리운_곰 2018.09.06 196
520 Prophet: Automatic Forecasting Procedure 자동 예측 프로시져 프로그램 /데이터분석 / 데이터 과학 file 졸리운_곰 2018.09.04 162
519 7 ways to convince MySQL to use the right index 졸리운_곰 2018.08.30 88
518 MYSQL에서 원치않는 TABLE LOCK이 걸렸을 경우 해제 방법입니다. 졸리운_곰 2018.08.29 118
517 제목 : [mysql] 현재날짜에서 이전달 구하기 file 졸리운_곰 2018.08.28 450
516 [mysql-함수]날짜 관련 함수 모음 졸리운_곰 2018.08.24 219
515 [질문]디비안에 있는 이번달에 입력된 자료만 뽑아 보고 싶거든요 졸리운_곰 2018.08.24 170
514 MYSQL 이번달 검색 쿼리 (말일,첫일 구하기) 졸리운_곰 2018.08.24 1333
513 MySQL 현재시간을 기준으로 (+, -) 시간 조회하기 - SUBDATE 졸리운_곰 2018.08.17 167
» How to INSERT If Row Does Not Exist (UPSERT) in MySQL 졸리운_곰 2018.08.16 138
511 Learn R in 15 Minutes file 졸리운_곰 2018.08.14 198
510 torch lua install on ubuntu 16.04 LTS [machine learning] 졸리운_곰 2018.08.13 190
509 How to kill MySQL connections 졸리운_곰 2018.08.02 181
508 MYSQL의 "too many connections" 에러 해결법 졸리운_곰 2018.08.02 52
507 [mysql] Too many connection 문제 해결 졸리운_곰 2018.08.02 93
506 [mysql] too many connections 에러 이유와 해결방안 file 졸리운_곰 2018.08.02 62
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED