Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search for multiple values in a column where I need to use wildcards?

In SQL Server, I need to search a column for multiple values, but I don't have the exact values, so I need to use wildcards as well.

My current query looks like this:

SELECT * 
FROM table 
WHERE fieldname in ( '%abc1234%',
                     '%cde456%',
                     '%efg8976%')

This doesn't return any results, and yet if I search for any one individual value, I find it, so I know they're in there. Short of doing multiple OR's, which is a bit unwieldy with several hundred values, is there a way to do this?

I'd also be interested to know why this query doesn't work, since the same query without the %'s works just fine (except for the small problem of only catching the few exact matches).

like image 663
Kirsten Avatar asked May 25 '12 03:05

Kirsten


People also ask

How do I use multiple wildcards in SQL?

There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations.

How do I query multiple values from the same column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

Can we use like for multiple values in SQL?

“The SQL LIKE operator allows performing logical evaluation for any matching records. Using the LIKE operator, you can specify single or multiple conditions. This allows you to perform an action such as select, delete, and updating any columns or records that match the specified conditions.

How do I select multiple values in SQL query?

To select multiple values, you can use where clause with OR and IN operator.


2 Answers

Look at using a Fulltext Index. That should do a much better job with your search, and make your "OR" problem a little nicer to boot:

SELECT * 
FROM table 
WHERE CONTAINS(fieldname, '"abc1234" OR "cde456" OR "efg8976"')

See also:

http://www.simple-talk.com/sql/learn-sql-server/full-text-indexing-workbench/

like image 171
Joel Coehoorn Avatar answered Sep 19 '22 22:09

Joel Coehoorn


The reason the query doesn't work is that it looks for an exact match for fieldname within the list of values in the parens. It doen't do a LIKE comparison where the wildcards are taken into account.

So your query is equivalent to:

SELECT *  from table  
where  fieldname  = '%abc1234%' OR
       fieldname  = '%cde456%' OR        
       fieldname  = '%efg8976%' 

Obviously not what you want.

like image 30
Andrew Cooper Avatar answered Sep 19 '22 22:09

Andrew Cooper