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?
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%';
Sample matches:
TestUser1
TestUser2
TestU
Test
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
Comparing strings with '=' is much faster.
In my small experience:
"=" for Exact Matches.
"LIKE" for Partial Matches.
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
Just as a heads up, the '=' operator will pad strings with spaces in Transact-SQL. So 'abc' = 'abc ' will return true; 'abc' LIKE 'abc ' will return false. In most cases '=' will be correct, but in a recent case of mine it was not.
So while '=' is faster, LIKE might more explicitly state your intentions.
http://support.microsoft.com/kb/316626
For pattern matching use LIKE. For exact match =.
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.
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.
There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:
declare #transid varchar(15)
if #transid != 0
will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.
Related
I have a database with workers and their names. How can I get a list of the workers whose name contains only 5 characters
What about this?
SELECT * FROM table_name WHERE island_name LIKE '_____'
Alternatively,
SELECT * FROM table_name WHERE REPLICATE('A',LEN(island_name)) = 'AAAAA'
You could use SUBSTRING(), if you are looking for an alternative method. You can check if a SUBSTRING of X characters == The Original String.
However, you would also need to account for 4-character strings, for example. You could add "padding characters", or you could make sure that X-1 Character Substring != X-character Substring. In Sql 2016 for example, these are the same with at least one case of query options:
SELECT SUBSTRING('ISLA',1,4)
SELECT SUBSTRING('ISLA',1,5)
I agree that LENGTH is the best option. Maybe this is a school question.
Give this a try:
SELECT SUBSTR(field1,1,5)
FROM table1
WHERE substr(field1,5,1) IS NOT NULL
AND SUBSTR(segment1,6,999) IS NULL;;
In my MariaDB environment I want to check to see if there are any values in the table "contacts" and the column "firstname", where the first letter in the string value is lower case. My question is: will this do the trick?
SELECT * FROM contacts
WHERE (firstname) LIKE '%[abcdefghijklmnopqrstuvwxyz]%';
MySQL does not support syntax [...] with LIKE.
You can also use the following condition to check if the first character of firstname is lowercased:
BINARY lower(left(firstname, 1)) = left(firstname, 1)
Another option is to use a regex (shorter to write and easier to understand):
BINARY firstname RLIKE '^[a-z]'
Please note that both expressions will not use an existing index on firstname, since functions or regexes comes into play.
In order for this to work in general, I believe you have to cast to binary:
cast(firstname as binary) rlike '^[a-z]'
Or:
cast(left(firstname, 1) as binary between 'a' and 'z'
I was practicing SQL injection skill, and I found that I could put = and LIKE in a single statement.
However, I'm not sure what does this mean and why it works?
SELECT 1 FROM users WHERE name='' LIKE '%'
So, what does that mean when I put = and LIKE in a statement, and when would I write something like this?
I am guessing that you are using MySQL, because this is syntactically correct in MySQL. It treats boolean types as numbers (which will be converted to integers and strings).
So, your code should be parsed as:
WHERE (name = '') LIKE '%'
This is because = and LIKE have the same precedence, and when operators have the same precedence, they are evaluated left-to-right (as explained in the documentation).
This, in turn evaluates to one of these three possibilities:
WHERE 1 LIKE '%' -- when name = ''
WHERE 0 LIKE '%' -- otherwise when name is not null
WHERE NULL like '%'
The first two will always evaluate to true. The third would discard any row where name is null.
(in MySQL and other popular DBMS) The LIKE operator is used to search for a specified pattern in a column. It admits "%" as a wildcard that represents zero, one, or multiple characters.
Your query always passes because the string '' meets this wildcard (zero characters). Incidentally, almost anything will. Some DBMS will react differently to such a query though.
1) select name from city where countrycode="JPN" ;
2) select name from city where countrycode='JPN' ;
3) select name from city where countrycode="jPn" ;
all the above queries are working in query 2 i am using single quotes and in 3 query i am using mixture of upper case and lowercase character . why it is producting correct output??.
I guess I misread the original question. Some database implementations are case insensitive are some aren't. Usually reserved keywords like SELECT, WHERE, etc.. are case-insensitive.
It might be worth forcing to lower or uppercase for your WHERE clause.
Consider using LOWER or UPPER to force lower or upper case
SELECT name from city where LCASE(countrycode) = "jpn"
I haven't used it personally so it might be worth benchmarking for speed.
Sorry I am new to working with databases - I am trying to perform a query
that will get all of the characters that are similar to a string in SQL.
For example,
If I am looking for all users that begin with a certain string, something like S* or Sm* that would return "Smith, Smelly, Smiles, etc..."
Am I on the right track with this?
Any help would be appreciated, and Thanks in advance!
Sql can't do this ... placing the percentage symbol in the middle.
SELECT * FROM users WHERE last_name LIKE 'S%th'
you would need to write a where clause and an and clause.
SELECT * FROM users WHERE last_name LIKE 'S%' and last_name LIKE '%th'
The LIKE operator is what you are searching for, so for your example you would need something like:
SELECT *
FROM [Users]
WHERE LastName LIKE 'S%'
The % character is the wild-card in SQL.
to get all the users with a lastname of smith
SELECT *
FROM [Users]
WHERE LastName ='Smith'
to get all users where the lastname contains smith do this, that will also return blasmith, smith2 etc etc
SELECT *
FROM [Users]
WHERE LastName LIKE '%Smith%'
If you want everything that starts with smith do this
SELECT *
FROM [Users]
WHERE LastName LIKE 'Smith%'
Standard (ANSI) SQL has two wildcard characters for use with the LIKE keyword:
_ (underscore). Matches a single occurrence of any single character.
% (percent sign). Matches zero or more occurrences of any single character.
In addition, SQL Server extends the LIKE wildcard matching to include character set specification, rather like a normal regular expresion character set specifier:
[character-set] Matches a single character from the specified set
[^character-set] Matches a single character not in the specified set.
Character sets may be specified in the normal way as a range as well:
[0-9] matches any decimal digit.
[A-Z] matches any upper-case letter
[^A-Z0-9-] matches any character that isn't a letter, digit or hyphen.
The semantics of letter matching of course, a dependent on the collation sequence in use. It may or may not be case-sensitive.
Further, to match a literal left square bracket ('[]'), you must use the character range specifier. You won't get a syntax error, but you won't get a match, either.
where x.field like 'x[[][0-9]]'
will match text that looks like 'x[0]' , 'x[8]', etc. But
where 'abc[x' like 'abc[x'
will always be false.
you might also like the results of SOUNDEX, depending on your preference for last name similarity.
select *
from [users]
where soundex('lastname') = soundex( 'Smith' )
or upper(lastname) like 'SM%'
Your question isn't entirely clear.
If you want all the users with last name Smith, a regular search will work:
SELECT * FROM users WHERE last_name = 'Smith'
If you want all the users beginning with 'S' and ending in 'th', you can use LIKE and a wildcard:
SELECT * FROM users WHERE last_name LIKE 'S%th'
(Note the standard SQL many wildcard of '%' rather than '*').
If you really want a "sounds like" match, many databases support one or more SOUNDEX algorithm searches. Check the documentation for your specific product (which you don't mention in the question).