RobM
RobM

Reputation: 256

SQL Like and like

Is it possible to string together multiple SQL LIKE wildcards in one query - something like this?

LIKE '% aaaa %' AND LIKE '% bbbb %'

The aim is to find records that contain both wild cards but in no specific order.

Upvotes: 5

Views: 45920

Answers (5)

Vyktor
Vyktor

Reputation: 20997

The correct SQL syntax is:

field LIKE '% aaaa %' AND field LIKE '% bbbb %'

Upvotes: 16

John Woo
John Woo

Reputation: 263723

This is useful when you are using this statement with variables.

SELECT * 
FROM `tableName`
WHERE `colName` LIKE CONCAT('%', 'aaaa', '%') AND -- if aaaa is direct Text
      `colName` LIKE CONCAT('%', 'bbbb', '%')

SELECT * 
FROM `tableName`
WHERE `colName` LIKE CONCAT('%', aaaa, '%') AND -- if aaaa is variable
      `colName` LIKE CONCAT('%', bbbb, '%')

Upvotes: 1

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

It is possible to string together an arbitrary number of conditions. However, it's prudent to use parenthesis to group the clauses to remove any ambiguity:

SELECT *
  FROM tableName
 WHERE (columnOne LIKE '%pattern%')
   AND (columnTwo LIKE '%other%')

Upvotes: 0

nickf
nickf

Reputation: 546045

Yes, but remember that LIKE is an operator similar to == or > in other languages. You still have to specify the other side of the equation:

SELECT * FROM myTable
WHERE myField LIKE '%aaaa%' AND myField LIKE '%bbbb%'

Upvotes: 0

Sparky
Sparky

Reputation: 15075

Yes, that will work, but the syntax is:

Field LIKE '%aaa%' AND field LIKE '%bbb%'

Upvotes: 2

Related Questions