Pregunta

How do you combine NOT IN and LIKE?

Let's assume we have a table that contains a column of names (something like 'blue cheese', 'gouda cheese' and so on) and I want to select all the names that doesn't contain 'cheese', 'milk', 'meat'.

As far as I understand to look for something that is not in an array of strings you use NOT IN and the pass the strings

SELECT names FROM some_table NOT IN('cheese','milk','meat');

but how do I pass

LIKE '%cheese%'

to it?

¿Fue útil?

Solución

The construct LIKE ANY (ARRAY[...]) appears to meet your needs;

craig=> SELECT a FROM (
           VALUES ('cheesy'), ('imilk'), ('donut'), ('pie'), ('avocado'), ('meaty')
        ) x(a) 
        WHERE NOT a LIKE ANY (ARRAY['%cheese%','%milk%','%meat%']);

    a    
---------
 cheesy
 donut
 pie
 avocado
(4 rows)

You need the wildcard characters if you want to use LIKE this way. If you really just want equality, you can use:

NOT = ANY (...)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top