Mysql – Find results with greatest difference

MySQL

I have a database which has a user's real age and the age that people have guessed them to look like in an uploaded photo.

I want to find the photos which have the greatest difference between guessed age and actual age. What Query could I run?

For example, the two rows that I am interested in are as follows.

age | avg
18 | 34.45
32 | 33.23
45 | 28.21

Thank you

Best Answer

The query below will return the maximum of the difference age from the guessed age:

SELECT MAX(DiffAge) AS MaxDifference
FROM (
    SELECT (`avg` - `age`) AS DiffAge 
    FROM `AgeTest`
) AS Result

Sample execution with given sample data:

CREATE TABLE `AgeTest` (`age` INT, `avg` numeric(18,2));

INSERT INTO `AgeTest` (`age`, `avg`) VALUES (18,34.45);
INSERT INTO `AgeTest` (`age`, `avg`) VALUES (32,33.23);
INSERT INTO `AgeTest` (`age`, `avg`) VALUES (45,28.21);

SELECT MAX(DiffAge) AS MaxDifference
FROM (
    SELECT (`avg` - `age`) AS DiffAge 
    FROM `AgeTest`
) AS Result

Working Demo: http://rextester.com/BSEEG25743