tags:

views:

70

answers:

1

How to find the nearest integer upon the provided one?

Say, I have the following integers in the mysql database: 405, 600, 304. The question is how to I select 600 upon providing 550 or select 304 upon providing 300 (ie, so as to find the nearest integer)?

i am talking about INTEGERS, not floats.

+8  A: 

If you have a table with a column containing some integers and you want to find the row with the integer closest to your input then use the following query:

To find the integer closest to 300:

SELECT column1
FROM table1
ORDER BY ABS(column1 - 300)
LIMIT 1

Result:

304

Or for input 550:

SELECT column1
FROM table1
ORDER BY ABS(column1 - 550)
LIMIT 1

Result:

600

Test data:

CREATE TABLE table1 (column1 INT NOT NULL);
INSERT INTO table1 (column1) VALUES
(405),
(600),
(304);
Mark Byers