How to update a column with the same values (not all) using UPDATE, SET and LIMIT in MySQL?

MySQLMySQLi Database

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('Adam');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+--------+
| Id | Name   |
+----+--------+
| 1  | Carol  |
| 2  | Chris  |
| 3  | David  |
| 4  | Bob    |
| 5  | Mike   |
| 6  | Sam    |
| 7  | Robert |
| 8  | Adam   |
+----+--------+
8 rows in set (0.00 sec)

Here is the query to update the table and set a column with the same values, except the last column value −

mysql> update DemoTable
   -> set Name="John"
   -> limit 7;
Query OK, 7 rows affected (0.20 sec)
Rows matched: 7 Changed: 7 Warnings: 0

Let us check the table records once again.

mysql> select *from DemoTable;

Output

+----+------+
| Id | Name |
+----+------+
| 1  | John |
| 2  | John |
| 3  | John |
| 4  | John |
| 5  | John |
| 6  | John |
| 7  | John |
| 8  | Adam |
+----+------+
8 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 12:53:17
Advertisements