Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find absolute difference between two numbers MYSQL

Tags:

mysql

What's the best way to find the absolute difference between two numbers in MYSQL so that I may order results? The below works, only if numberA is larger than numberB, but as you can see this is not always the case. Is there a good way to do this with one statement?

SELECT (numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

|-------------------|
| numberA | numberB |
| 5.4     | 2.2     |
| 7.7     | 4.3     |
| 1       | 6.5     |
| 2.3     | 10.8    |
| 4.5     | 4.5     |
like image 785
user1145643 Avatar asked May 23 '14 17:05

user1145643


People also ask

How do I find the difference between two numbers in SQL?

The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. 0 indicates weak or no similarity between the SOUNDEX values. 4 indicates strong similarity or identically SOUNDEX values.

Is there a difference function in MySQL?

To count the difference between dates in MySQL, use the DATEDIFF(enddate, startdate) function. The difference between startdate and enddate is expressed in days. In this case, the enddate is arrival and the startdate is departure .


1 Answers

As simple as that:

SELECT ABS(numberA - numberB) AS spread 
FROM table 
ORDER BY spread DESC

Or, if you want to select the pair (numberA, numberB) in descending order of their difference:

SELECT numberA, numberB
FROM table 
ORDER BY ABS(numberA - numberB) DESC
like image 157
John Bupit Avatar answered Sep 25 '22 19:09

John Bupit