tags:

views:

8563

answers:

7

Hi!

There's the (almost religious) discussion, if you should use LIKE or '=' to compare strings in SQL statements.

  • Are there reasons to use LIKE?
  • Are there reasons to use '='?
  • Performance? Readability?

Thanks in advance!

+1  A: 

For pattern matching use LIKE. For exact match =.

Techmaddy
+1  A: 

LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.

Gishu
+1  A: 

In my small experience:

"=" for Exact Matches.

"LIKE" for Partial Matches.

Stu Andrews
+27  A: 

LIKE and the equality operator have different purposes, they don't do the same thing: = is much faster, whereas LIKE can interpret wildcards. Use = wherever you can and LIKE wherever you must.

SELECT * FROM user WHERE login LIKE 'Test%';
-- Matches
--   TestUser1
--   TestUser2
--   TestU
--   Test
--   etc.
soulmerge
And no, it does *not* match the string 'etc.' :)
soulmerge
Nice comment! :)
furtelwart
+1  A: 

LIKE is used for pattern matching and = is used for equality test (as defined by the COLLATION in use).

= can use indexes while LIKE queries usually require testing every single record in the result set to filter it out (unless you are using full text search) so = has better performance.

Mehrdad Afshari
+8  A: 

To see the performance difference, try this:

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name
Techmaddy
Woops... okay, I took the point.Table with ~600 entries, 10 digit number as comparing field:Equal is 20 to 30 times faster!
furtelwart
Talking about performance when talking about “=” and “LIKE” is, like, you know, maximum fail.
Bombe
A: 

There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):

ILIKE, which is a case insensitive LIKE match:

select * from people where name ilike 'JOHN'

Matches:

  • John
  • john
  • JOHN

And if you want to get really mad you can use regular expressions:

select * from people where name ~ 'John.*'

Matches:

  • John
  • Johnathon
  • Johnny
Ceilingfish
But that does not beat the performance of "=", does it?
furtelwart
As far as I am aware the regular expression and like keywords have worse performance than '='
Ceilingfish