Select equal or nearest greater number from table in MySQL


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)

Updated on: 03-Mar-2020

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements