How to find absolute difference between two numbers in MySQL?

MySQLMySQLi Database

To get the difference between two number in MySQL, let us first create a demo table

mysql> create table findDifferenceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstNumber float,
   -> SecondNumber float
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(4.2,2.3);
Query OK, 1 row affected (0.20 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(23.4,5.6);
Query OK, 1 row affected (0.14 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(5.8,34.56);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(7.8,7.2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into findDifferenceDemo(FirstNumber,SecondNumber) values(12.8,10.2);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from findDifferenceDemo;

The following is the output

+----+-------------+--------------+
| Id | FirstNumber | SecondNumber |
+----+-------------+--------------+
| 1  | 4.2         |          2.3 |
| 2  | 23.4        |          5.6 |
| 3  | 5.8         |        34.56 |
| 4  | 7.8         |          7.2 |
| 5  | 12.8        |         10.2 |
+----+-------------+--------------+
5 rows in set (0.00 sec)

The following is the query to find absolute difference between two numbers in MySQL

mysql> SELECT ABS(FirstNumber - secondNumber) AS diff
   -> from findDifferenceDemo
   -> order by diff desc;

The following is the output

+--------------------+
| diff               |
+--------------------+
| 28.760001182556152 |
| 17.799999713897705 |
| 2.6000003814697266 |
| 1.8999998569488525 |
| 0.6000003814697266 |
+--------------------+
5 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 11:59:29
Advertisements