If new, INSERT. if existing, UPDATE. - MySQL (ON DUPLICATE KEY UPDATE)

If new, INSERT. if existing, UPDATE. - MySQL (ON DUPLICATE KEY UPDATE)

Create test_table and add 2 records.
CREATE TABLE IF NOT EXISTS `test_table` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `test_table` (`id`, `name`, `email`) VALUES
(1, 'sam1', 'sam1@xx.com'),
(2, 'sameera', 'sameera@xx.com');






Insert id '1' again with different data.
INSERT INTO test_table(id, name, email)
     VALUES ('1', 'sam1', 'sam1@xx.com')
     ON DUPLICATE KEY UPDATE
     id = values(id),
     name = values(name),
     email= values(email);







Record will update

No comments:

Post a Comment