Limiting numbers to a maximum value in MySQL?

MySQLMySQLi Database

For this, you can use LEAST(). Following is the syntax −

select least(yourColumnName,yourMaxValue) from yourTableName;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Number int
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

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

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------+
| Number |
+--------+
| 50     |
| 40     |
| 30     |
| 201    |
| 60     |
+--------+
5 rows in set (0.00 sec)

Here is the query to limit numbers to a maximum value in MySQL. We have limited all the numbers to a maximum value 40 −

mysql> select least(Number,40) from DemoTable;

Output

+------------------+
| least(Number,40) |
+------------------+
| 40               |
| 40               |
| 30               |
| 40               |
| 40               |
+------------------+
5 rows in set (0.02 sec)
raja
Published on 09-Jul-2019 16:04:07
Advertisements