SQL NOT EQUAL Operator
The SQL NOT EQUAL operator is used to filter records that do not match a specified value. In SQL, the != or <> operators can be used interchangeably to represent “not equal to”. This operator is commonly used in the WHERE clause to exclude specific values from query results.
In this tutorial, we will explore the NOT EQUAL operator in SQL with syntax explanations and practical examples.
Syntax of SQL NOT EQUAL != Operator
The basic syntax for using the NOT EQUAL operator in a WHERE clause is as follows:
</>
Copy
SELECT column1, column2, ...
FROM table_name
WHERE column_name != value;
Alternatively, you can use the <> operator:
</>
Copy
SELECT column1, column2, ...
FROM table_name
WHERE column_name <> value;
Explanation:
- SELECT: Specifies the columns to retrieve from the table.
- FROM: Specifies the table from which data is selected.
- WHERE: Filters records based on conditions.
- != or <>: Ensures that the values in the column are not equal to the specified value.
Step-by-Step Examples Using SQL NOT EQUAL != Operator
1 Filtering Employees Who Are Not from a Specific Department
Let’s create an employees table to demonstrate the NOT EQUAL operator.
</>
Copy
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10,2)
);
Insert some sample data:
</>
Copy
INSERT INTO employees (name, department, salary)
VALUES
('Arjun', 'IT', 75000),
('Ram', 'HR', 60000),
('John', 'Finance', 80000),
('Priya', 'IT', 72000),
('David', 'Marketing', 65000);
Now, let’s fetch employees who are NOT in the IT department:
</>
Copy
SELECT * FROM employees
WHERE department != 'IT';
