Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
javamonkey79 Avatar asked Dec 31 '08 23:12

javamonkey79


People also ask

What is the difference between like and wildcards in SQL?

A wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

What can I use instead of like in SQL?

You may come across the situation, where you need alternate to “like” keyword of SQL, that is to search for sub-string in columns of the table. The one way to achieve it to use instr() function, instr() function takes 3 parameters in account .

Which one is not the correct wildcard used with like keyword?

The answer to the last question in the previous paragraph is that underscore ('_') is not a regular character for the LIKE clause, but a wildcard character. Unlike literal characters, wildcard characters have specific meaning for the LIKE operator.

What is like and not like in SQL?

The SQL LIKE and NOT LIKE operators are used to find matches between a string and a given pattern. They are part of standard SQL and work across all database types, making it essential knowledge for all SQL users.


3 Answers

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.

like image 150
Christian C. Salvadó Avatar answered Oct 12 '22 22:10

Christian C. Salvadó


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  '
like image 39
CSharpie Avatar answered Oct 12 '22 21:10

CSharpie


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

like image 7
Otávio Décio Avatar answered Oct 12 '22 22:10

Otávio Décio