How to properly use LIKE statement in sql query - sql

I have database which contains a field named groupid and group name.
sample data
groupid groupname
123 abc
234 bcr
1237 cde
I like to compare groupid with another inputted data, its size is greater than size of group id.
I tried a query that not return correct answer
SELECT *
FROM mydata
WHERE groupid LIKE '12309098';
My expected answer is abc
What are the changes to made for correct answer
thanks in advance

Since you want the value in the row to be the prefix of your input and not the other way around, you can just turn LIKE around the other way;
SELECT *
FROM mydata
WHERE '12309098' LIKE CONCAT(groupid, '%');
An SQLfiddle to test with;
EDIT: Since you asked about SQLite, there you need to use || for concatenation;
SELECT *
FROM mydata
WHERE '12309098' LIKE `groupid` || '%';
Another SQLfiddle.

You could do like below:
SELECT *
FROM my data
WHERE '12309098' LIKE CONCAT('%', groupid, '%');

You could use something like this. But it is highly subjective to your SQL Server. For Oracle following syntax should be fine
SELECT *
FROM mydata
WHERE groupid LIKE SUBSTR('12309098',1, LENGTH(groupid));

If you are sure that input data will start with 123, then:
SELECT * FROM mydata WHERE groupid LIKE '123%';
If you are sure that input data will contain 123, then:
SELECT * FROM mydata WHERE groupid LIKE '%123%';

Related

Using CONTAINS to find items IN a table

I'm trying to write a SP that will allow users to search on multiple name strings, but supports LIKE functionality. For example, the user's input might be a string 'Scorsese, Kaurismaki, Tarkovsky'. I use a split function to turn that string into a table var, with one column, as follows:
part
------
Scorsese
Kaurismaki
Tarkovsky
Then, normally I would return any values from my table matching any of these values in my table var, with an IN statement:
select * from myTable where lastName IN (select * from #myTableVar)
However, this only returns exact matches, and I need to return partial matches. I'm looking for something like this, but that would actually compile:
select * from myTable where CONTAINS(lastName, select * from #myTableVar)
I've found other questions where it's made clear that you can't combine LIKE and IN, and it's recommended to use CONTAINS. My specific question is, is it possible to combine CONTAINS with a table list of values, as above? If so, what would that syntax look like? If not, any other workarounds to achieve my goal?
I'm using SQL Server 2016, if it makes any difference.
You can use EXISTS
SELECT * FROM myTable M
WHERE
EXISTS( SELECT * FROM #myTableVar V WHERE M.lastName like '%'+ V.part +'%' )
Can your parser built the entire statement? Will that get you what you want?
select *
from myTable
where CONTAINS
(lastName,
'"Scorsese" OR "Kaurismaki" OR "Tarkovsky"'
)
This can be done using CHARINDEX function combined with EXISTS:
select *
from myTable mt
where exists(select 1 from #myTableVar
where charindex(mt.lastName, part) > 0
or charindex(part, mt.lastName) > 0)
You might want to omit one of the conditions in the inner query, but I think this is what you want.

Concatenating strings in PostgreSQL result

I have an SQL query like this:
SELECT DISTINCT(id) FROM users WHERE ...
and I would like to display the results like that:
user=12355
user=78949
user=9898
user=489891
Basically with "user=" prepended. Is it possible to do this with PostgreSQL? I've tried with STRING_AGG('user=', DISTINCT(id)) but got an error on DISTINCT(id). Any idea?
I'd use a plain GROUP BY for this.
SELECT format('user=%s',id)
FROM users
GROUP BY id;
http://sqlfiddle.com/#!1/39727/3
This will be considerably more efficient than using DISTINCT on the string concatenation.
You should be able to use || for string concatenation:
SELECT DISTINCT('user=' || id)
FROM users
WHERE ...
SQL Fiddle Demo
This might be useful as well:
http://www.postgresql.org/docs/current/static/functions-string.html
The only reason you got an error message from string_agg() is because you forgot the second parameter which is required. This very simple query would just work:
SELECT string_agg('user=' || id, E'\n')
FROM users
WHERE ...
E'\n' .. newline character
Produces one row with the exactly the string you have in your question.
You do not need either DISTINCT or GROUP BY unless you have duplicates in id - in which case you'd need a subquery:
SELECT string_agg('user=' || id, E'\n')
FROM (SELECT id FROM users GROUP BY id) x
Simply
Select concat('user=',id) from users

sql searching multiple words in a string

What is the most efficient and elegant SQL query looking for a string containing the words "David", "Moses" and "Robi". Assume the table is named T and the column C.
Select * from table where
columnname like'%David%' and
columnname like '%Moses%' and columnname like'%Robi%'
In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:
SELECT *
FROM T
WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');
If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:
SELECT *
FROM T
WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');
Here is what I uses to search for multiple words in multiple columns - SQL server
Hope my answer help someone :) Thanks
declare #searchTrm varchar(MAX)='one two three ddd 20 30 comment';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
If you care about the sequence of the terms, you may consider using a syntax like
select * from T where C like'%David%Moses%Robi%'
Oracle SQL :
select *
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles database')
company - is the database column name.
results - this SQL will show you if company column rows contain one of those companies (OR phrase)
please note that : no wild characters are needed, it's built in.
more info at : http://www.techonthenet.com/oracle/regexp_like.php
if you put all the searched words in a temporaray table say #tmp and column col1, then you could try this:
Select * from T where C like (Select '%'+col1+'%' from #temp);
Maybe EXISTS can help.
and exists (select 1 from #DocumentNames where pcd.Name like DocName+'%' or CD.DocumentName like DocName+'%')
Oracle SQL:
There is the "IN" Operator in Oracle SQL which can be used for that:
select
namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi');

How to give the output of the first query(which has two values) as the input to the second?

i get 2 names as the output of the first query....
eg: paul,peter
now this should be the input for the second query,
which has to display paul's and peter's email ids....
For nested queries I would strongly recommend WITH clause. It makes long complex queries order of magnitude easier to understand / construct / modify:
WITH
w_users AS( -- you can name it whatever you want
SELECT id
FROM users
WHERE < long condition here >
),
w_other_subquery AS(
...
)
SELECT email_id
FROM ...
WHERE user_id IN (SELECT id FROM w_users)
You can use like this
LIKE
SELECT USER_ID,EMAIL_ID FROM USERS where user_id IN
(SELECT PRODUCT_MEMBERS FROM PRODUCT WHERE PRODUCT_NAME='ICP/RAA');
Just use the IN clause '=' is used for matching one result
You can use In Command to get result
ex:
SELECT email FROM tableName WHERE (Name IN ('paul', 'peter'))

Is there any way to combine IN with LIKE in an SQL statement?

I am trying to find a way, if possible, to use IN and LIKE together. What I want to accomplish is putting a subquery that pulls up a list of data into an IN statement. The problem is the list of data contains wildcards. Is there any way to do this?
Just something I was curious on.
Example of data in the 2 tables
Parent table
ID Office_Code Employee_Name
1 GG234 Tom
2 GG654 Bill
3 PQ123 Chris
Second table
ID Code_Wildcard
1 GG%
2 PQ%
Clarifying note (via third-party)
Since I'm seeing several responses which don't seems to address what Ziltoid asks, I thought I try clarifying what I think he means.
In SQL, "WHERE col IN (1,2,3)" is roughly the equivalent of "WHERE col = 1 OR col = 2 OR col = 3".
He's looking for something which I'll pseudo-code as
WHERE col IN_LIKE ('A%', 'TH%E', '%C')
which would be roughly the equivalent of
WHERE col LIKE 'A%' OR col LIKE 'TH%E' OR col LIKE '%C'
The Regex answers seem to come closest; the rest seem way off the mark.
I'm not sure which database you're using, but with Oracle you could accomplish something equivalent by aliasing your subquery in the FROM clause rather than using it in an IN clause. Using your example:
select p.*
from
(select code_wildcard
from second
where id = 1) s
join parent p
on p.office_code like s.code_wildcard
In MySQL, use REGEXP:
WHERE field1 REGEXP('(value1)|(value2)|(value3)')
Same in Oracle:
WHERE REGEXP_LIKE(field1, '(value1)|(value2)|(value3)')
Do you mean somethign like:
select * FROM table where column IN (
SELECT column from table where column like '%%'
)
Really this should be written like:
SELECT * FROM table where column like '%%'
Using a sub select query is really beneficial when you have to pull records based on a set of logic that you won't want in the main query.
something like:
SELECT * FROM TableA WHERE TableA_IdColumn IN
(
SELECT TableA_IdColumn FROM TableB WHERE TableA_IDColumn like '%%'
)
update to question:
You can't combine an IN statement with a like statement:
You'll have to do three different like statements to search on the various wildcards.
You could use a LIKE statement to obtain a list of IDs and then use that in the IN statement.
But you can't directly combine IN and LIKE.
Perhaps something like this?
SELECT DISTINCT
my_column
FROM
My_Table T
INNER JOIN My_List_Of_Value V ON
T.my_column LIKE '%' + V.search_value + '%'
In this example I've used a table with the values for simplicity, but you could easily change that to a subquery. If you have a large list (like tens of thousands) then performance might be rough.
select *
from parent
where exists( select *
from second
where office_code like trim( code_wildcard ) );
Trim code_wildcard just in case it has trailing blanks.
You could do the Like part in a subquery perhaps?
Select * From TableA Where X in (Select A from TableB where B Like '%123%')
tsql has the contains statement for a full-text-search enabled table.
CONTAINS(Description, '"sea*" OR "bread*"')
If I'm reading the question correctly, we want all Parent rows that have an Office_code that matches any Code_Wildcard in the "Second" table.
In Oracle, at least, this query achieves that:
SELECT *
FROM parent, second
WHERE office_code LIKE code_wildcard;
Am I missing something?