In Postgres 9.4 or later, use the dedicated aggregate FILTER
clause:
SELECT count(*) FILTER (WHERE col ILIKE '%crackers%') AS ct_cracker
, count(*) FILTER (WHERE col ILIKE '%soda%') AS ct_soda
, count(*) FILTER (WHERE col ILIKE ALL ('{%crackers%, %soda%}'::text[]) AS ct_both
FROM tbl
WHERE col ILIKE ANY ('{%crackers%, %soda%}'::text[]);
There are a couple of standard techniques that work for older versions or MySQL, too:
Assuming you want case-insensitive pattern matching, hence ILIKE
.
The ANY
and ALL
constructs are handy features, especially for longer arrays, but not strictly necessary for your problem. Also, the WHERE
clause is not strictly needed, but typically improves performance.
Details: