MySQL Not Equal Operator
MySQL Not Equal Operator
The MySQL !=
or <>
operator is used to compare two values. This operator is essential for filtering records where one value is not equal to another.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column1 != value;
SELECT column1, column2, ...
FROM table_name
WHERE column1 <> value;
The !=
and <>
operators have the following components:
column1, column2, ...
: The columns to be retrieved.table_name
: The name of the table from which to retrieve the data.column1 != value
orcolumn1 <> value
: The condition to filter the records, wherecolumn1
is not equal to a specifiedvalue
.
Example MySQL Not Equal Operator
Let's look at some examples of the MySQL !=
and <>
operators:
Step 1: Using the Database
USE mydatabase;
This query sets the context to the database named mydatabase
.
Step 2: Creating a Table
Create a table to work with:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
department VARCHAR(50),
salary DECIMAL(10, 2)
);
This query creates a table named employees
with columns for id
, first_name
, last_name
, department
, and salary
.
Step 3: Inserting Initial Rows
Insert some initial rows into the table:
INSERT INTO employees (first_name, last_name, department, salary)
VALUES ('John', 'Doe', 'HR', 50000.00),
('Jane', 'Smith', 'IT', 60000.00),
('Jim', 'Brown', 'IT', 55000.00),
('Jake', 'White', 'HR', 52000.00),
('Jill', 'Green', 'Marketing', 45000.00);
This query inserts five rows into the employees
table.
Step 4: Using Not Equal Operator with WHERE Clause
Use the !=
operator to filter records based on a condition:
SELECT *
FROM employees
WHERE department != 'IT';
This query retrieves all columns from the employees
table where the department
is not equal to 'IT'.
Step 5: Using Not Equal Operator with Multiple Conditions
Use the !=
operator with multiple conditions:
SELECT *
FROM employees
WHERE department != 'HR' AND salary != 50000.00;
This query retrieves all columns from the employees
table where the department
is not 'HR' and the salary
is not 50000.00.
Step 6: Using Not Equal with Multiple Columns
Use the !=
operator with multiple columns:
SELECT first_name, last_name
FROM employees
WHERE department != 'Marketing' AND salary != 45000.00;
This query retrieves the first_name
and last_name
columns from the employees
table where the department
is not 'Marketing' and the salary
is not 45000.00.
Conclusion
The MySQL !=
and <>
operators are powerful tools for filtering records based on a comparison condition. Understanding how to use the !=
and <>
operators is essential for effective data querying and analysis in MySQL.