T-SQL Tutorial

NOT Query


In SQL Server, the NOT query is used as a logical operator to negate a condition in a SQL statement. It is often combined with other clauses like SELECT, WHERE, JOIN, etc., to filter or exclude records based on a specified condition. The NOT operator is employed to retrieve records that do not meet the specified criteria.

Here are some common use cases for the NOT query in SQL Server:


NOT EQUAL TO (<>)

SELECT * FROM TableName
WHERE ColumnName <> 'SomeValue';

This query retrieves all records from the specified table where the value in the specified column is not equal to 'SomeValue'.


NOT LIKE

SELECT * FROM TableName
WHERE ColumnName NOT LIKE 'Pattern%';

This query retrieves all records where the value in the specified column does not match the specified pattern.


NOT IN

SELECT * FROM TableName
WHERE ColumnName NOT IN ('Value1', 'Value2', 'Value3');

This query retrieves all records where the value in the specified column is not present in the list provided.


NOT EXISTS

SELECT * FROM Table1
WHERE NOT EXISTS (SELECT 1 FROM Table2 WHERE Table1.ID = Table2.ID);

This query retrieves all records from Table1 where there is no corresponding record in Table2 based on a specified condition.


NOT BETWEEN

SELECT * FROM TableName
WHERE ColumnName NOT BETWEEN 10 AND 20;

This query retrieves all records where the value in the specified column does not fall within the specified range.


NOT NULL

SELECT * FROM TableName
WHERE ColumnName IS NOT NULL;

This query retrieves all records where the value in the specified column is not NULL.

These are just a few examples of how the NOT query can be used in SQL Server to filter or exclude records based on specific conditions. It's a powerful tool for constructing flexible and precise queries to retrieve the data that meets your requirements.

It's important to note that the effectiveness of the NOT operator depends on the specific conditions and requirements of your query. Be mindful of how you structure your queries to ensure accurate and desired results.