6

Are there any differences in the results of these two queries other than performance?

SELECT * FROM pet WHERE name LIKE 'Spot';
SELECT * FROM pet WHERE name = 'Spot';

Reason I ask is the real script will be something like the following and the API user is responsible to come up with the pattern. More often that not, a LIKE pattern will be provided, but there is always a chance that just a string will be provided resulting in SELECT * FROM pet WHERE name LIKE "Spot".

$stmt = $this->pdo->prepare('SELECT * FROM pet WHERE name LIKE ?');
$stmt->execute([$_GET['name']]); //Spot
return [$stmt->fetchAll(),200];
Your Common Sense
  • 154,967
  • 38
  • 205
  • 325
user1032531
  • 22,993
  • 61
  • 191
  • 346
  • If a DBMS is following Standard SQL there is a difference when there are trailing spaces, `name like 'Spot'` will not match `'Spot '`, but `=` will. – dnoeth Feb 26 '17 at 15:06

2 Answers2

8

In practice, LIKE with no wildcards is functionally equivalent to =. However, they are not the same! The obvious difference is that = doesn't treat \, %, and _ in any special way, but LIKE does.

The documentation is pretty clear on this:

Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator:

In addition to collation differences, trailing spaces matter:

In particular, trailing spaces are significant, which is not true for CHAR or VARCHAR comparisons performed with the = operator:

In practice, the strings being compared usually have the same collation, don't have trailing spaces, and special characters are ignored, so LIKE is sometimes used as a replacement for = (especially because LIKE without wildcards at the beginning of the pattern can also make use of an index).

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
1

Effectively, it turns out to be the same thing in your example, but here is more info:

From another stackoverflow answer

= is a comparison operator that operates on numbers and strings. When comparing strings, the comparison operator compares whole strings.

LIKE is a string operator that compares character by character.

Community
  • 1
  • 1
user1333394
  • 696
  • 6
  • 6