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.
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;;
I have two columns, one for 'firstName' and one for 'lastName'. I'm trying to perform a where operation on the concatenation of those two columns to match for a full name.
Here is what I've tried:
select * from table where concat_ws(' ', 'firstName', 'lastName') like '%some_value%'
This just returns a blank array.
Example Data:
firstName
lastName
Clayton
Smith
Barbara
Clayman
Sam
Peterson
when some_value = Clay, it should return 'Clayton Smith' and 'Barbara Clayman'
I got a lot of this syntax from some other stackoverflow answers which were marked as solutions to a similar problem, however when implementing this myself I couldn't get it to work.
FWIW I'm going to be building these queries with knex.js so if there's a knex.js specific solution feel free to answer with that.
The arguments to your CONCAT_WS call should be in double quotes. If they're in single quotes, Postgres will interpret them as string literals. This should work:
SELECT * FROM table WHERE CONCAT_WS(' ', "firstName", "lastName") ILIKE '%some_value%'
I also recommend using ILIKE rather than LIKE - this will make the pattern matching for your search term be case insensitve.
use STR_POS
The PostgreSQL strpos() function is used to find the position, from where the substring is being matched within the string.
https://w3resource.com/PostgreSQL/strpos-function.php#:~:text=The%20PostgreSQL%20strpos()%20function,being%20matched%20within%20the%20string.&text=Example%20of%20PostgreSQL%20STRPOS(),within%20the%20argument%20is%205.
select * from table where strpos(concat_ws(' ', first_name, last_name),'Clay') > 0
Replace literal with variable
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.
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
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).