Skip to content

Instantly share code, notes, and snippets.

@saniyathossain
Forked from brennanMKE/mysql_upsert.sql
Created February 2, 2021 14:47
Show Gist options
  • Save saniyathossain/06355bec993508f6d95e80eccdae7d92 to your computer and use it in GitHub Desktop.
Save saniyathossain/06355bec993508f6d95e80eccdae7d92 to your computer and use it in GitHub Desktop.
MySQL Upsert
DROP TABLE IF EXISTS `things`;
CREATE TABLE `things` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nbr` int(11) NOT NULL,
`thing` varchar(255) NOT NULL,
`createdAt` datetime NOT NULL DEFAULT NOW(),
`updatedAt` datetime NOT NULL DEFAULT NOW() ON UPDATE NOW(),
PRIMARY KEY (`id`),
UNIQUE KEY `nbr_unique` (`nbr`)
);
INSERT INTO `things` (nbr,thing) VALUES (1, 'A Thing') ON DUPLICATE KEY UPDATE thing = 'A Thing';
SELECT * FROM `things`;
INSERT INTO `things` (nbr,thing) VALUES (1, 'Another Thing') ON DUPLICATE KEY UPDATE thing = 'Another Thing';
SELECT * FROM `things`;
DELETE FROM `things`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment