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'
Related
I have SQL table where username have different cases for example "ACCOUNTS\Ninja.Developer" or "ACCOUNTS\ninja.developer"
I want to find the how many records where username where first in first and last name capitalize ? how can use Regex to find the total ?
x table
User
"ACCOUNTS\James.McAvoy"
"ACCOUNTS\michael.fassbender"
"ACCOUNTS\nicholas.hoult"
"ACCOUNTS\Oscar.Isaac"
Do you want something like this?
select count(*)
from t
where name rlike 'ACCOUNTS\[A-Z][a-z0-9]*[.][A-Z][a-z0-9]*'
Of course, different databases implement regular expressions differently, so the actual comparator may not be rlike.
In SQL Server, you can do:
select count(*)
from t
where name like 'ACCOUNTS\[A-Z][^.][.][A-Z]%';
You might need to be sure that you have a case-sensitive collation.
In most cases in MS SQL string collation is case insensitive so we need some trick. Here is an example:
declare #accts table(acct varchar(100))
--sample data
insert #accts values
('ACCOUNTS\James.McAvoy'),
('ACCOUNTS\michael.fassbender'),
('ACCOUNTS\nicholas.hoult'),
('ACCOUNTS\Oscar.Isaac')
;with accts as (
select
--cleanup and split values
left(replace(acct,'ACCOUNTS\',''),charindex('.',replace(acct,'ACCOUNTS\',''),0)-1) frst,
right(replace(acct,'ACCOUNTS\',''),charindex('.',replace(acct,'ACCOUNTS\',''),0)) last
from #accts
)
,groups as (--add comparison columns
select frst, last,
case when CAST(frst as varbinary(max)) = CAST(lower(frst) as varbinary(max)) then 'lower' else 'Upper' end frstCase, --circumvert case insensitive
case when CAST(last as varbinary(max)) = CAST(lower(last) as varbinary(max)) then 'lower' else 'Upper' end lastCase
from accts
)
--and gather fruit
select frstCase, lastCase, count(frst) cnt
from groups
group by frstCase,lastCase
Your question is a little vague but;
You might be looking for the DISTINCT command.
REF
I don't think you need regex.
Maybe do something like:
Get distinct names from Table X as Table A
Use inputs table A as where clause on Table X
count
union
I hope this helps,
Rhys
Given your example set you can use a combination of techniques. First if the user name always begins with "ACCOUNTS\" then you can use substr to select the characters that start after the "\" character.
For the first name:
Then you can use a regex function to see if it matches against [A-Z] or [a-z] assuming your username must start with an alpha character.
For the last name:
Use the instr function on the substr and search for the character '.' and again apply the regex function to match against [A-Z] or [a-z] to see if the last name starts with an upper or a lower character.
To total:
Select all matches where both first and last match against upper and do a count. Repeat for the lower matches and you'll have both totals.
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';
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).
How do I do this?
For example, if my column is "cats,dogs,birds" and I want to get any rows where column contains cats?
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.
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.