Skip to content

Instantly share code, notes, and snippets.

@addiks
Created January 8, 2019 15:22
Show Gist options
  • Save addiks/b3f507a45dc12e9f6b09b7b42740c823 to your computer and use it in GitHub Desktop.
Save addiks/b3f507a45dc12e9f6b09b7b42740c823 to your computer and use it in GitHub Desktop.
Demonstration of a MERGE in MySQL that only applies when same PK
CREATE TABLE `sandbox`.`new_table` (
`id` INT NOT NULL,
`name` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC));
INSERT INTO new_table
(id, name, email)
VALUES
(123, 'John Doe', 'john.doe@example.com');
# Different PK, other entity (different identity):
# 0 row(s) affected
INSERT INTO new_table
(id, name, email)
VALUES
(456, 'John Jimmy Doe', 'john.doe@example.com')
ON DUPLICATE KEY
UPDATE name=IF(id != VALUES(id), name, VALUES(name));
# Same PK, same entity (same identity):
# 2 row(s) affected
INSERT INTO new_table
(id, name, email)
VALUES
(123, 'John Jimmy Doe', 'john.doe@example.com')
ON DUPLICATE KEY
UPDATE name=IF(id != VALUES(id), name, VALUES(name));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment