MySQL update multiple rows in one query
In this exercise, we will learn to update multiple rows with different values in one query. Suppose we have the following employee records and we want to update the phone number of some employees -
CREATE TABLE IF NOT EXISTS `empdata` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(25) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `empdata` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Anjali', 'anjali@example.com', 878433948),
(2, 'Priska', 'priska@example.com', 493905490),
(3, 'Abhi', 'abhi@example.com', 403022139),
(4, 'Joya', 'joya@example.com', 342345329),
(5, 'Ammy', 'ammy@example.com', 239848342),
(6, 'Lussi', 'lussi@example.com', 490290331);
The best way to update multiple rows in just one statement is use CASE WHEN ELSE statement. In this, the statement will update the matched case and end otherwise, like-
Here, 'table_name' is the MySQL table name, 'field_name' is the column name.
The update query to update the phone number of some employees are as follows -
let's check the updated data-
need an explanation for this answer? contact us directly to get an explanation for this answer+----+--------+--------------------+-----------+ | id | name | email | phone | +----+--------+--------------------+-----------+ | 6 | Lussi | lussi@example.com | 909030309 | | 4 | Joya | joya@example.com | 342345329 | | 5 | Ammy | ammy@example.com | 239848342 | | 2 | Priska | priska@example.com | 890040908 | | 3 | Abhi | abhi@example.com | 675748389 | | 1 | Anjali | anjali@example.com | 840932345 | +----+--------+--------------------+-----------+