36

Normally, when querying a database with SELECT, its common to want to find the records that match a given search string.

For example:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

That query should give me all records where 'Bob Smith' appears anywhere in the name field.

What I'd like to do is the opposite.

Instead of finding all the records that have 'Bob Smith' in the name field, I want to find all the records where the name field is in 'Robert Bob Smith III, PhD.', a string argument to the query.

2
  • 4
    Not sure I understand. Can you make an example? Commented Feb 6, 2011 at 21:20
  • Have to agree with @Pekka. Perhaps if you supply a few example sets of input data you're expecting matches for and the relevant search term(s). Commented Feb 6, 2011 at 21:21

3 Answers 3

51

Just turn the LIKE around

SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')
Sign up to request clarification or add additional context in comments.

4 Comments

Exactly it. I tried this but didn't do it with CONCAT on the end. Works like a charm. Thx.
Will this result in a full table scan? Is there a solution that uses an index?
@landon9720 Yes. The only index that can possibly be used is a FULLTEXT index
in case you are using sqlite, you can concat the strings with '||' operator SELECT * FROM customers WHERE 'Robert Bob Smith III, PhD.' LIKE '%' || name || '%' ;
12

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

1 Comment

I am using REGXP on a 200,000 row DB, and it does not bring a whole bunch...
-6

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

1 Comment

It seems like you didn't understand the original question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.