How to work with “!=” or “not equals” in MySQL WHERE?

MySQLMySQLi Database

You can use the != or not equals like <>. The syntax is as follows −

select *from yourTableName where <> conditionValue;

To understand the above syntax, let us create a table. The query to create a table.

mysql> create table NotEqualsDemo
−> (
   −> Id int
−> );
Query OK, 0 rows affected (1.03 sec)

You can insert some records in the table with the help of insert command. The query is as follows −

mysql> insert into NotEqualsDemo values(1);
Query OK, 1 row affected (0.15 sec)

mysql> insert into NotEqualsDemo values(2);
Query OK, 1 row affected (0.18 sec)

mysql> insert into NotEqualsDemo values(3);
Query OK, 1 row affected (0.10 sec)

mysql> insert into NotEqualsDemo values(4);
Query OK, 1 row affected (0.18 sec)

mysql> insert into NotEqualsDemo values(5);
Query OK, 1 row affected (0.14 sec)

Now you can display all records with the help of select statement. The query is as follows −

mysql> select *from NotEqualsDemo;

The following is the output −

+------+
| Id   |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
+------+
5 rows in set (0.00 sec)

Now you can implement the syntax which I have discussed in the beginning. The below query will give all results except value 3 because we have applied the concept of not equals like <> 3.

The query is as follows −

mysql> select *from NotEqualsDemo where Id <> 3;

The following is the output −

+------+
| Id   |
+------+
| 1    |
| 2    |
| 4    |
| 5    |
+------+
4 rows in set (0.00 sec)
raja
Published on 10-Jan-2019 12:00:51
Advertisements