javamonkey79
javamonkey79

Reputation: 17795

SQL LIKE with no wildcards the same as '='?

I know this is a pretty basic question, and I think I know the answer...but I'd like to confirm.

Are these queries truly equivalent?

SELECT * FROM FOO WHERE BAR LIKE 'X'
SELECT * FROM FOO WHERE BAR ='X'

Perhaps there is a performance overhead in using like with no wild cards?

I have an app that optionally uses LIKE & wild cards. The SP currently does the like and appends the wild cards -- I am thinking of just updating the query to use like but have the app append the wild cards as needed.

Upvotes: 56

Views: 31068

Answers (4)

Diego Alonso
Diego Alonso

Reputation: 133

I found one case where using LIKE is 20x - 125x faster than using = (which goes to show that armchair philosophizing about "what the optimizer would do" is not as easy as some would think, or people vastly overestimate the intelligence of these tools even on very simple tasks).

It's a database with ~50 million rows.

Create a trigram GIN index:

CREATE EXTENSION pg_trgm;
CREATE INDEX  ON profiles  USING gin (username gin_trgm_ops);

And now one query takes 200 ms, while the the other takes 4 - 25 secs.

SELECT userid,username,country  FROM profiles  WHERE username LIKE 'someuser';
SELECT userid,username,country  FROM profiles  WHERE username='someuser';

Upvotes: 1

CSharpie
CSharpie

Reputation: 9477

Original Answer by Matt Whitfield from here

There is a difference between = and LIKE. When you perform string comparisons by using LIKE, all characters in the pattern string are significant. This includes leading or trailing spaces.

So if you have a column that is char or nchar and not nvarchar or varchar, there will be different results due to trailing spaces.

Small example to reproduce this behaviour:

CREATE TABLE #temp (nam [varchar](MAX))
INSERT INTO [#temp] ([nam])
VALUES ('hello')
INSERT INTO [#temp] ([nam])
VALUES ('hello  ')

SELECT * FROM #temp WHERE [nam] = 'hello  '

SELECT * FROM #temp WHERE [nam] LIKE 'hello  '

Upvotes: 23

Christian C. Salvadó
Christian C. Salvadó

Reputation: 828090

As @ocdecio says, if the optimizer is smart enough there should be no difference, but if you want to make sure about what is happening behind the scenes you should compare the two query's execution plans.

Upvotes: 33

Otávio Décio
Otávio Décio

Reputation: 74310

Any good optimizer would reduce the first expression to the second.

Upvotes: 7

Related Questions