How to update a range of records in MySQL?


To update a range of records in MySQL, you can use BETWEEN. Let us first create a table:

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Age int
);
Query OK, 0 rows affected (0.53 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Age) values('Chris',21);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Carol',25);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Age) values('David',22);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Robert',26);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('John',20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name,Age) values('Johnny',28);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('James',23);
Query OK, 1 row affected (0.23 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+----+--------+------+
| Id | Name | Age |
+----+--------+------+
| 1 | Larry | 23 |
| 2 | Sam | 24 |
| 3 | Chris | 21 |
| 4 | Carol | 25 |
| 5 | David | 22 |
| 6 | Robert | 26 |
| 7 | John | 20 |
| 8 | Mike | 27 |
| 9 | Johnny | 28 |
| 10 | James | 23 |
+----+--------+------+
10 rows in set (0.00 sec)

Following is the query to update a range of records in MySQL. We are updating the Name to ‘Bob’ for Ids in the range 5 to 10:

mysql> update DemoTable set Name='Bob', Age=23 where Id between 5 AND 10;
Query OK, 6 rows affected (0.25 sec)
Rows matched: 6 Changed: 6 Warnings: 0

Let us now display all records including updated records:

mysql> select *from DemoTable;

This will produce the following output

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry | 23   |
|  2 | Sam   | 24   |
|  3 | Chris | 21   |
|  4 | Carol | 25   |
|  5 | Bob   | 23   |
|  6 | Bob   | 23   |
|  7 | Bob   | 23   |
|  8 | Bob   | 23   |
|  9 | Bob   | 23   |
| 10 | Bob   | 23   |
+----+-------+------+
10 rows in set (0.00 sec)

Updated on: 30-Jul-2019

735 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements