Select equal or nearest greater number from table in MySQL

MySQLMySQLi Database

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(25);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(75);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    25 |
|    75 |
|   100 |
+-------+
3 rows in set (0.00 sec)

Here is the query to select equal or nearest greater number from the table −

mysql> select * from DemoTable
   -> order by abs(Value-50), Value desc
   -> limit 1;

This will produce the following output−

+-------+
| Value |
+-------+
|    75 |
+-------+
1 row in set (0.00 sec)
raja
Published on 12-Dec-2019 05:36:19
Advertisements