Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the correct, or preferable, not equal operator in MySQL

Which of the two (semantically equivalent) ways is preferable to test for inequality?

  1. 'foo' != 'bar' (exclamation mark and equals sign)
  2. 'foo' <> 'bar' (less than and greater than chevron symbols together)

The MySQL documentation clearly indicates that there is no difference between them and yet some people seem to be attached to only doing it one way or the other. Maybe this is just another pointless vi vs. emacs debate but when other people are reading your code (and therefore your queries), it's useful to maintain some consistency.

<> looks a lot like <=> which is a very underused operator but could perhaps lead to confusion at a quick glance since the two are nearly opposite (except for the obvious NULL cases).

like image 698
Rob Van Dam Avatar asked Jan 14 '10 19:01

Rob Van Dam


People also ask

How do you write not equal in MySQL query?

not equal to (<>, !=) operator. MySQL Not equal is used to return a set of rows (from a table) after making sure that two expressions placed on either side of the NOT EQUAL TO (<>) operator are not equal.

Can you use != In SQL?

There is no != operator according to the ANSI/SQL 92 standard.

How do you use the not equal to operator?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .


2 Answers

<> should be preferred, all things being equal, since it accords with the sql standard and is technically more portable...

!= is non-standard, but most db's implement it.

sql:2008 grammar:

<not equals operator> ::=   <> 
like image 135
jspcal Avatar answered Sep 26 '22 17:09

jspcal


It's obvious.

The ! character is on the North West corner of US keyboards.

Microsoft headquarters are in the North West corner of the US.

So. <> is a nod to Microsoft.

!= is a rejection of Microsoft.

It's a secret political code.

like image 45
S.Lott Avatar answered Sep 25 '22 17:09

S.Lott