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 86633
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79011
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95764
13 [데이터 수집 및 전처리] 주식 전종목 어떻게 불러올까? 거래소 종목 불러오기 file 졸리운_곰 2023.12.09 1702
12 [데이터 수집 및 전처리] [Python/파이썬]네이버증권API 활용 - 회사명, 종목코드 받아오기 file 졸리운_곰 2023.12.08 1510
11 [데이터 수집 및 전처리] 네이버 금융(차트)에서 주가 갈무리(크롤링)하기 file 졸리운_곰 2023.12.08 1497
10 [데이터 수집 및 전처리] 네이버 증권에서 일봉, 주봉 데이터 가져오기 file 졸리운_곰 2023.12.08 1501
9 [데이터 수집 및 전처리] (놀라운) 한글 데이터 짱! AwesomeKorean_Data file 졸리운_곰 2023.03.07 1198
8 [데이터 수집 및 전처리] Crawling, Scraping file 졸리운_곰 2022.05.21 1476
7 [데이터분석][데이터수집 전처리] MS 엑셀(Excel)에서 UTF-8 로 된 csv 파일 가져오기 file 졸리운_곰 2021.09.30 1416
6 카프카 설치 시 가장 중요한 설정 4가지 졸리운_곰 2021.07.13 1930
5 Prometheus Query(PromQL) 기본 이해하기 file 졸리운_곰 2020.12.17 1414
4 [인프라 모니터링 오픈소스] Prometheus 를 알아보자 file 졸리운_곰 2020.12.17 1912
3 Prometheus + Grafana 대시보드 file 졸리운_곰 2020.12.17 2490
2 Grafana란? file 졸리운_곰 2020.12.17 2159
1 Importing wikipedia dump to MySql 졸리운_곰 2020.10.04 2495
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED