How to SELECT records if the absolute value of the difference between two values is greater than a certain number?


To SELECT records if the absolute value of the difference between two values is greater than a certain number, following is the syntax:

select *from yourTableName where abs(yourColumnName1-yourColumnName2) >= yourCertainNumber;

Let us first create a table:

mysql> create table DemoTable
(
   Number1 int ,
   Number2 int
);
Query OK, 0 rows affected (0.59 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(10,20);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(100,200);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(400,300);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(1000,500);
Query OK, 1 row affected (0.15 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output

+---------+---------+
Number1   | Number2 |
+---------+---------+
| 10      | 20      |
| 100     | 200     |
| 400     | 300     |
| 1000    | 500     |
+---------+---------+
4 rows in set (0.00 sec)

Let us now write a query to SELECT records if the absolute value of the difference between two values is greater than a certain number. Here, our number is 100, with which the absolute value will be compared:

mysql> select *from DemoTable where abs(Number1-Number2) > 100;

This will produce the following output:

+---------+---------+
| Number1 | Number2 |
+---------+---------+
| 1000    | 500     |
+---------+---------+
1 row in set (0.02 sec)

Updated on: 30-Jul-2019

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements