Implement GREATEST() in MySQL and update the table?


Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Number int
   );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Number) values(10);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Number) values(50);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Number) values(100);
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Number) values(190);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  1 | 10     |
|  2 | 50     |
|  3 | 100    |
|  4 | 190    |
+----+--------+
4 rows in set (0.00 sec)

Following is the query to update greatest() in MySQL −

mysql> update DemoTable set Number=GREATEST(200,Number) WHERE Id=3;
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us display table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  1 | 10     |
|  2 | 50     |
|  3 | 200    |
|  4 | 190    |
+----+--------+
4 rows in set (0.00 sec)
raja
Published on 17-May-2019 17:20:20
Advertisements