0

Below line from this page shows how to match based upon end characters.

select * from table where Name like '%es'

How could I modify the code if I want to match with multiple values. For example I have another table T2 that has column C1 and I want all values from column Name that end in values from column C1

if I want to find all Names that are in C1, I would use

 select * from table where Name in (select C1 from T2)

on a similar lines I want something like below. It is a pseudo code

  select * from table where Name like (select '%C1' from T2)

Column C1 and Name have thousands of values in them

3
  • What's your dbms? Commented Aug 29, 2018 at 20:58
  • Possible duplicate of How to use LIKE statement with multiple values from another field? Commented Aug 29, 2018 at 20:59
  • Which DBMS are you using? "SQL" is just a query language, not the name of a specific database product. Please add the tag for the database product you are using postgresql, oracle, db2, sql-server, ... Commented Aug 31, 2018 at 19:05

2 Answers 2

2

You can try to use exists and subquery makes LIKE column value by + or || depend on your DBMS.

select * 
from table t1
where exists(
   SELECT 1 
   FROM T2 
   WHERE t1.Name LIKE '%' + T2.C1
) 

or

select * 
from table t1
where exists(
   SELECT 1 
   FROM T2 
   WHERE t1.Name LIKE '%' || T2.C1
) 

Here is a mysql sample.

CREATE TABLE T1(
   Name varchar(50)
);

INSERT INTO T1 VALUES ('cat hat');
INSERT INTO T1 VALUES ('cat aaa');

CREATE TABLE T2(
   C1 varchar(50)
);

INSERT INTO T2 VALUES ('cat');

Query 1:

select * 
from  t1
where exists(
   SELECT C1 
   FROM t2
   WHERE t1.Name LIKE '%' || T2.C1
) 

Results:

|    Name |
|---------|
| cat hat |
| cat aaa |
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. What is the purpose of SELECT 1 FROM T2 ?
The EXISTS operator is used to test for the existence of any record in a subquery. select 1 mean get the value from the condition, you can also use SELECT * FROM T2 depend on you
0

Let's say, we need to get column1, column2 from tablename, in which column2 ends with either A or B or C:

Then we can simply write below query:`

SELECT column1, column2, ...
FROM tablename
WHERE RIGHT(column2,1) in ('A','B','C');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.