Computer >> Computer tutorials >  >> Programming >> MySQL

Using “not equal” in MySQL?


If you want to work with not equal operator, then use the <> operator. The syntax is as follows −

SELECT *FROM yourTableName WHERE yourColumnName <> anyValue;

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

mysql> create table NotEqualDemo
-> (
-> ProductId int
-> );
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into NotEqualDemo values(101);
Query OK, 1 row affected (0.13 sec)

mysql> insert into NotEqualDemo values(102);
Query OK, 1 row affected (0.23 sec)

mysql> insert into NotEqualDemo values(103);
Query OK, 1 row affected (0.11 sec)

mysql> insert into NotEqualDemo values(104);
Query OK, 1 row affected (0.13 sec)

mysql> insert into NotEqualDemo values(105);
Query OK, 1 row affected (0.12 sec)

Let us now display all records from the table using select command. The query is as follows −

mysql> select *from NotEqualDemo;

The following is the output −

+-----------+
| ProductId |
+-----------+
| 101       |
| 102       |
| 103       |
| 104       |
| 105       |
+-----------+
5 rows in set (0.00 sec)

Here we are using <> operator to filter the data which is not equal to 104. In this, all the data will be displayed except 104. The query is as follows −

mysql> select *from NotEqualDemo where ProductId <> 104 or ProductId is null;

The following is the output −

+-----------+
| ProductId |
+-----------+
| 101       |
| 102       |
| 103       |
| 105       |
+-----------+
4 rows in set (0.00 sec)