In PostgreSQL how to combine NOT IN and LIKE?
Asked Answered
A

1

1

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?

Acicula answered 31/5, 2013 at 9:47 Comment(0)
F
5

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 (...)
Fizgig answered 31/5, 2013 at 15:14 Comment(2)
@boo_boo_bear: Or WHERE a !~~ ALL (...) / WHERE a <> ALL (...) if there are no NULL values involved.Amelioration
Why where "ID" not like any ( array['RC11909%','RC11917%','RC14755%','RC14990%']) doesn't work but where not "ID" like any ( array['RC11909%','RC11917%','RC14755%','RC14990%']) works as expected?Molybdenum

© 2022 - 2024 — McMap. All rights reserved.