11/16: MySQL > Updating Data (INSERT & REPLACE)
Category: Study
Posted by: hajime osako
If both the column list and the VALUES list are empty, MySQL creates a new record with each column set to its default:
INSERT INTO table_name () VALUES();
When you have many records to add, multiple-row statements provide better performance (but may reach the max_allowed_packet size.)
In error condition for multiple record INSERT statements, MyISAM inserts the records until the error record, but for InnoDB, the entire statement fails and no records are inserted.
INSERT ... ON DUPLICATE KEY UPDATE clause allows you to do in one statement what otherwise requires two (INSERT and UPDATE).
INSERT INTO log_table (id, date_time, counter)
VALUES (1, NOW(), 1)
ON DUPLICATE KEY UPDATE counter=counter+1;
Note: If an already existing record is updated, the "rows affected" value is 2.
If a table contains multiple unique-valued indexes, REPLACE replaces each of those records (deletes the matching multiple rows, then inserts one row.)
REPLACE requires the INSERT and DELETE privilege.
INSERT INTO table_name () VALUES();
When you have many records to add, multiple-row statements provide better performance (but may reach the max_allowed_packet size.)
In error condition for multiple record INSERT statements, MyISAM inserts the records until the error record, but for InnoDB, the entire statement fails and no records are inserted.
INSERT ... ON DUPLICATE KEY UPDATE clause allows you to do in one statement what otherwise requires two (INSERT and UPDATE).
INSERT INTO log_table (id, date_time, counter)
VALUES (1, NOW(), 1)
ON DUPLICATE KEY UPDATE counter=counter+1;
Note: If an already existing record is updated, the "rows affected" value is 2.
If a table contains multiple unique-valued indexes, REPLACE replaces each of those records (deletes the matching multiple rows, then inserts one row.)
REPLACE requires the INSERT and DELETE privilege.