Should I use != or <> for not equal in T-SQL?

Viewed 1145954

I have seen SQL that uses both != and <> for not equal. What is the preferred syntax and why?

I like !=, because <> reminds me of Visual Basic.

14 Answers

Most databases support != (popular programming languages) and <> (ANSI).

Databases that support both != and <>:

Databases that support the ANSI standard operator, exclusively:

  • IBM DB2 UDB 9.5: <>
  • Microsoft Access 2010: <>

Technically they function the same if you’re using SQL Server AKA T-SQL. If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant.

You can find links to the various ANSI standards at...

http://en.wikipedia.org/wiki/SQL

'<>' is from the SQL-92 standard and '!=' is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.

In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.

It seems that Microsoft themselves prefer <> to != as evidenced in their table constraints. I personally prefer using != because I clearly read that as "not equal", but if you enter [field1 != field2] and save it as a constrait, the next time you query it, it will show up as [field1 <> field2]. This says to me that the correct way to do it is <>.

You can use whichever you like in T-SQL. The documentation says they both function the same way. I prefer !=, because it reads "not equal" to my (C/C++/C# based) mind, but database gurus seem to prefer <>.

I understand that the C syntax != is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).

Both works and I think any difference would be very negligible! Just focus on productivity guys!

What is the value of your script? What does it do? How will it contribute to the business? Will it make more money?

Focus on these goals instead of these programmer prefered preferences. This is like which is better C# or Visual Basic languages. As if the end user cares what was used to write the App?

What the end user cares about is what your App could do. How could it help him with what he is doing.

Related