Contents
SQL NOT: Definition and Syntax
By using SQL NOT
, you can negate a specified condition, which means the value must be the opposite of the defined condition to be selected. The syntax for defining an SQL NOT
condition is simple:
NOT condition
Just like AND and OR, SQL NOT
is usually used in the WHERE clause. It can be included in various statements, such as INSERT, SELECT, UPDATE or DELETE:
SELECT column_demo1, column_demo2, ...
FROM table_demo
WHERE NOT condition;
Example of Using NOT in SQL
To help you get a better idea on how SQL WHERE NOT
works, we'll provide a few code examples for you to try. Get familiar with the data table we'll be using, and move on to practice.
A Demo Database
For our example, we will be using a Developers table in the database:
ID | Name | City | Country |
---|---|---|---|
1 | Tom Kurkutis | New York | USA |
2 | Ana Fernandez | London | UK |
3 | Antonio Indigo | Paris | France |
4 | Aarav Kaelin | Delhi | India |
5 | Andrew Tumota | Miami | USA |
6 | Basma Zlata | Miami | USA |
Using SQL NOT
In the code example below, you can see a line that says WHERE NOT Country='UK';
. This means the SELECT
statement will only select those fields in the Developers table which have another value defined in the Country
column:
Combining AND, OR and NOT in SQL
You can combine NOT
with the AND and OR operators to achieve more specific results.
In this code example, we select the fields from the Developers table which have a country defined that is NOT France AND NOT India:
SELECT * FROM Developers
WHERE NOT Country='France' AND NOT Country='India';
Now, we select the fields which have the country defined as USA AND the city specified as either Miami OR New York:
SELECT * FROM Developers
WHERE Country='USA' AND (City='Miami' OR City='New York');