Combine two columns and perform a where operation on the result - sql

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

Related

SQL fetch results by concatenating words in column

I have column store_name (varchar). In that column I have entries like prime sport, best buy... with a space. But when user typed concatenated string like primesport without space I need to show result prime sport. how can I achieve this? Please help me
SELECT *
FROM TABLE
WHERE replace(store_name, ' ', '') LIKE '%'+#SEARCH+'%' OR STORE_NAME LIKE '%'+#SEARCH +'%'
Well, I don't have much idea, and even I am searching for it. But may be what I know works for you, You can achieve this by performing different type of string operations:
Mike can be Myke or Myce or Mikke or so on.
Cat an be Kat or katt or catt or so on.
For this you should write a function to generate number of possible strings and then form a SQL Query using all these, and query the database.
A similar kind of search in known as Soundex Search from Oracle and Soundex Search from Microsoft. Have a look of it. this may work.
And overall make use of functions like upper and lower.
Have you tried using replace()
You can replace the white space in the query then use like
SELECT * FROM table WHERE replace(store_name, ' ', '') LIKE '%primesport%'
It will work for entries like 'prime soft' querying with 'primesoft'
Or you can use regex.

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

SQL Wildcard Question

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

MySQL match existence of a term amongst comma seperated values using REGEXP

I have a MySQL select statement dilemma that has thrown me off course a little. In a certain column I have a category term. This term could look something like 'category' or it could contain multiple CSV's like this: 'category, bank special'.
I need to retrieve all rows containing the term 'bank special' in the comma separated value. Currently I am using the following SQL statement:
SELECT * FROM tblnecklaces WHERE nsubcat REGEXP 'bank special';
Now this works OK, but if I had the category as follows: 'diamond special' for example then the row is still retrieved because the term 'special' in my column seems to be matching up to the term 'bank special' in my REGEXP statement.
How would I go abut checking for the existence of the whole phrase 'bank special' only and not partially matching the words?
Many thanks for your time and help
The simplest solution is to use the LIKE clause (% is wildcard):
SELECT * FROM tblnecklaces WHERE nsubcat LIKE '%bank special%';
Note that LIKE is also a lot faster than REGEXP.
You can prefix the column with comma's, and compare it to the bank special:
SELECT *
FROM tblnecklaces
WHERE ',' + replace(nsubcat,', ','') + ',' LIKE ',bank special,'
I put in a replace to remove optional space after a comma, because your example has one.
Not tested but this RegExp should work (LIKE works too but will match items that starts or ends with the same phrase):
SELECT * FROM tblnecklaces WHERE nsubcat REGEXP '(^|, )bank special($|,)';

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.