Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for inequality in T-SQL

I've just come across this in a WHERE clause:

AND NOT (t.id = @id) 

How does this compare with:

AND t.id != @id 

Or with:

AND t.id <> @id 

I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <> or != is going to bust any hopes for using an index that I might have had, but surely the first approach above will suffer the same problem?

like image 886
ninesided Avatar asked Aug 11 '08 15:08

ninesided


People also ask

How do you check for equal conditions in SQL?

In SQL, you can use the = operator to test for equality in a query. In this example, the SELECT statement above would return all rows from the suppliers table where the supplier_name is equal to Microsoft.

Do we use == in SQL?

The sql equal operator is used to check whether two expressions are equal or not. If it's equal, the condition will be true and will return matched records. The sql not equal operator is used to check whether two expressions are equal or not.

What does >= mean in SQL?

>= (Greater Than or Equal To) (Transact-SQL) - SQL Server | Microsoft Docs.


2 Answers

These 3 will get the same exact execution plan

declare @id varchar(40) select @id = '172-32-1176'  select * from authors where au_id <> @id  select * from authors where au_id != @id  select * from authors where not (au_id = @id) 

It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself

like image 144
SQLMenace Avatar answered Sep 22 '22 17:09

SQLMenace


Note that the != operator is not standard SQL. If you want your code to be portable (that is, if you care), use <> instead.

like image 20
DannySmurf Avatar answered Sep 24 '22 17:09

DannySmurf