How can I return a record from a table nearest to a user-defined variables value in MySQL?


Let us first create a table −

mysql> create table DemoTable
(
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProductAmount int
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ProductAmount) values(5000);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ProductAmount) values(6000);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(ProductAmount) values(7000);
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+---------------+
| CustomerId | ProductAmount |
+------------+---------------+
|          1 |          5000 |
|          2 |          6000 |
|          3 |          7000 |
+------------+---------------+
3 rows in set (0.00 sec)

Following is the query to return the nearest value. Here, we have set a user-defined variable with value 6990. Therefore, now we need to fetch the record nearest to 6990 −

mysql> set @value=6990;
Query OK, 0 rows affected (0.00 sec)
mysql> select ProductAmount from DemoTable order by ABS(ProductAmount-@value) LIMIT 1;

This will produce the following output −

+---------------+
| ProductAmount |
+---------------+
|          7000 |
+---------------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements