SQL Wildcard Question - sql

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).

Related

SQL query to exclude numbers, brackets or special characters at the end of a name

I'm trying to exclude all names with numbers in it, but still include certain special characters like:
()-'
So far, i've got this query:
SELECT FirstName FROM Client WHERE FirstName NOT LIKE '%[^0-9]%';
This excludes most names with numbers in it, however, a few like the following are still coming through (not being excluded):
How do i exclude these from above, but still keep rows that look like the ones below:
Thank you in advance!
I'm trying to exclude all names with numbers in it.
Assuming you are using SQL Server, your logic has too many negations. You want:
WHERE FirstName NOT LIKE '%[0-9]%';
This translates to FirstName not having any number in it.
If you want names that are only alphabetical and spaces, then use:
WHERE FirstName NOT LIKE '%[^a-zA-Z ]%';
Your version simply states that the string has no character which is not like a digit -- that is, it consists only of digits.

Regular Expression "a{2}" not working

I have a record with emp_name = "Rajat" and it is not getting returned.
My query is -
SELECT * FROM employees WHERE emp_name regexp "a{2}"
Please explain why it is not working
Your regex search for aa
https://www.regex101.com/r/yA1qA2/1
What you need is:
a.*a
https://www.regex101.com/r/hA5yS8/1
a{2} means two consecutive as. Your string doesn't match it.
To match a string with two a characters that might not be consecutive characters you should use a.*a.
a{2} will match two straight a characters, i.e.: aa.
To match 2 alternate a characters you can use:
select * from employees where emp_name REGEXP "^.*a.*a.*$";
I think all you need is LIKE with %:
LIKE - Simple pattern matching
Character Description
% Matches any number of characters, even zero
characters
_ Matches exactly one character
LIKE pattern match... succeeds only if the pattern matches the entire value
So, you can use a more specific
select * from employees where emp_name like '%a_a%';
Or, a more "generic" (allowing more characters than 1 between a and a:
select * from employees where emp_name like '%a%a%';
However, since in MySQL, SQL patterns are case-insensitive by default, so, you might have to use REGEXP with BINARY to narrow down your search results:
Prior to MySQL 3.23.4, REGEXP is case sensitive.
From MySQL 3.23.4 on, if you really want to force a REGEXP comparison
to be case sensitive, use the BINARY keyword to make one of the
strings a binary string.
SELECT * FROM employees WHERE emp_name REGEXP BINARY 'a.*a';

Matching exactly 2 characters in string - SQL

How can i query a column with Names of people to get only the names those contain exactly 2 “a” ?
I am familiar with % symbol that's used with LIKE but that finds all names even with 1 a , when i write %a , but i need to find only those have exactly 2 characters.
Please explain - Thanks in advance
Table Name: "People"
Column Names: "Names, Age, Gender"
Assuming you're asking for two a characters search for a string with two a's but not with three.
select *
from people
where names like '%a%a%'
and name not like '%a%a%a%'
Use '_a'. '_' is a single character wildcard where '%' matches 0 or more characters.
If you need more advanced matches, use regular expressions, using REGEXP_LIKE. See Using Regular Expressions With Oracle Database.
And of course you can use other tricks as well. For instance, you can compare the length of the string with the length of the same string but with 'a's removed from it. If the difference is 2 then the string contained two 'a's. But as you can see things get ugly real soon, since length returns 'null' when a string is empty, so you have to make an exception for that, if you want to check for names that are exactly 'aa'.
select * from People
where
length(Names) - 2 = nvl(length(replace(Names, 'a', '')), 0)
Another solution is to replace everything that is not an a with nothing and check if the resulting String is exactly two characters long:
select names
from people
where length(regexp_replace(names, '[^a]', '')) = 2;
This can also be extended to deal with uppercase As:
select names
from people
where length(regexp_replace(names, '[^aA]', '')) = 2;
SQLFiddle example: http://sqlfiddle.com/#!4/09bc6
select * from People where names like '__'; also ll work

VB6 Syntax Question

Can anyone tell me what this Asterisk(*) is for. ...tblpersonal where empid like '" & idNumber & "*'". What if I replace it with Percent sign(%), what would be the outcome?
The LIKE condition allows you to use wildcards in the where clause of an SQL statement. This allows you to perform pattern matching. The LIKE condition can be used in any valid SQL statement - select, insert, update, or delete.
The patterns that you can choose from are:
% allows you to match any string of any length (including zero length)
_ allows you to match on a single character
Next, let's explain how the _ wildcard works. Remember that the _ is looking for only one character.
For example,
SELECT * FROM suppliers
WHERE supplier_name like 'Sm_th';
This SQL statement would return all suppliers whose name is 5 characters long, where the first two characters is 'Sm' and the last two characters is 'th'. For example, it could return suppliers whose name is 'Smith', 'Smyth', 'Smath', 'Smeth', etc.
Here is another example,
SELECT * FROM suppliers
WHERE account_number like '12317_';
The same way u can use asterisk (*) instead of (%)
I hope its help to you
The Percent (%) sign in SQL says "match any number of characters here". E.g. LIKE '%test' will match abctest, LIKE 'test%' will match testabc
The Asterisk character looks like it'll match a literal *, e.g. matching all empids ending with an asterisk (depending on the version of SQL - see below)
EDIT: See Microsoft Jet wildcards: asterisk or percentage sign? for a more in depth answer on * vs %
This is much more a SQL syntax question than a VB6 one. :-)
You haven't mentioned what database this is talking to (I assume it's talking to a DB). The asterisk is not generally special in SQL (or VB6 strings), and so that query will look for empid being like whatever's in your idNumber followed by an asterisk. Probably not what was intended. If you replace it with a %, you'll be looking for any empid that starts with whatever's in your idNumber variable. If the column is numeric, it will be converted to text before the comparison.
So for instance, if idNumber contains 100, say, and there are empid values in the database with the values 10, 100, 1000, and 10000, the query would match all but the first of those, since "100", "1000", and "10000" are all like "100%".

Ignoring spaces between words - an SQL question

I want to grab from a db a record with name='John Doe'.
I'd like my query to also grab 'John(4 spaces between)Doe','John(2 spaces betwewen)Doe' etc. (at least one space however).
I'd also like that the case won't matter, so I can also get 'John Doe' by typing
'john doe' etc.
Try this:
SELECT * FROM table WHERE lower(NAME) like 'john%doe%'
use like with wildcards (e.g. %) to get around the spaces and the lower (orlcase) to be case insensitive.
EDIT:
As the commenters pointed out, there are two shortcomings within this solution.
First: you will select "johnny doe" or worse "john Eldoe", or worse, "john Macadoelt" with this query, so you'll need extra filtering on the application side.
Second: using a function can lead to table scans instead of index scans. This may be avoided, if your dbms supports function based indexes. See this Oracle example
If your database has Replace function
Select * From Table
Where Upper(Replace(name, ' ', '')) = 'JOHNDOE'
The rest of these will return rows where the middle part between John and Doe is anything, not just spaces...
if your database has left function and Reverse, Try either
Select * From Table
Where left(Upper(name), 4) = 'JOHN'
And Left(Reverse(Upper(name), 3)) = 'EOD'
else use substring and reverse
Select * From Table
Where substring(Upper(name), 4) = 'JOHN'
And substring(Reverse(Upper(name), 3)) = 'EOD'
or Like operator
Select * From Table
Where Upper(name) Like 'JOHN%DOE'
In MYSQL:
select user_name from users where lower(trim(user_name)) regexp 'john[[:blank:]]+doe' = 1;
Explanation:
In the above case the user_name matches the regular expression john(one or more spaces)doe. The comparison is case insensitive and trim takes care of spaces before and after the string.
In case the search string contains special characters, they need to be escaped. More in mysql documentation: http://dev.mysql.com/doc/refman/5.5/en/regexp.html
In sql you can use wildcards, that is a character that stands in place of other characters. for example:
select * from table where name like 'john%doe'
will select all names that start with john and end with doe no matter how many characters in between.
This article explains more and gives some options.
The wildcard will match on zero characters, so if you want at least one space then you should do
select * from table where lower(name) like 'john %doe'
In Oracle you can do:
SELECT * FROM table
WHERE UPPER(REGEXP_REPLACE(NAME,'( ){2,}', ' ') = 'JOHN DOE';
No false positives like 'john mordoe' etc.