MySQL Select Rows where two columns do not have the same value?

MySQLMySQLi Database

You can use != operator from MySQL for this. The syntax is as follows:

SELECT *FROM yourTableName
WHERE yourColumnName1 !=yourColumnName2
OR (yourColumnName1 IS NULL AND yourColumnName2IS NOT NULL)
OR (yourColumnName2 IS NULL AND yourColumnName1 IS NOT NULL);

To understand the above syntax, let us create a table. The query to create a table is as follows:

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

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

mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(10,20);
Query OK, 1 row affected (0.29 sec)
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(30,40);
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(20,20);
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,60);
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(50,50);
Query OK, 1 row affected (0.17 sec)
mysql> insert into selectTwoColumns(FirstNumber,SecondNumber) values(70,NULL);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from selectTwoColumns;

The following is the output:

+----+-------------+--------------+
| Id | FirstNumber | SecondNumber |
+----+-------------+--------------+
|  1 |          10 |           20 |
|  2 |          30 |           40 |
|  3 |          20 |           20 |
|  4 |          50 |           60 |
|  5 |          50 |           50 |
|  6 |          70 |         NULL |
+----+-------------+--------------+
6 rows in set (0.00 sec)

Here is the query to select rows where two columns do not have same value:

mysql> select *from selectTwoColumns
   -> where FirstNumber!=SecondNumber
   -> OR (FirstNumber IS NULL AND SecondNumber IS NOT NULL)
   -> OR (SecondNumber IS NULL AND FirstNumber IS NOT NULL);

The following is the output:

+----+-------------+--------------+
| Id | FirstNumber | SecondNumber |
+----+-------------+--------------+
|  1 |          10 |           20 |
|  2 |          30 |           40 |
|  4 |          50 |           60 |
|  6 |          70 |         NULL |
+----+-------------+--------------+
4 rows in set (0.00 sec)
raja
Published on 25-Feb-2019 09:50:29
Advertisements