I'm writing an inefficient query as follows:
WHERE (Field iLIKE '%cat%' OR Field iLIKE '%dog%' OR Field iLIKE '%animal%' OR Field iLIKE '%pet%')
whereas what I would like to write is:
WHERE Field iLIKE ('%cat%','%dog%','%animal%','%pet%')
Is there an easy way to accomplish this?
You can get the powerful regular expression operators ~
and ~*
for case insensitive:
WHERE Field ~* '(cat|dog|animal|pet)'
SIMILAR TO
is case sensitive, so you'd have to do:
WHERE Field SIMILAR TO '%([Cc][Aa][Tt]|[Dd][Oo][Gg]|[Aa][Nn][Ii][Mm][Aa][Ll]|[Pp][Ee][Tt])%'
ANY ARRAY
will work too, but the perfomance is worse:
WHERE Field ILIKE ANY (array['%cat%','%dog%','%animal%','%pet%'])
With some dummy data with 1000000 rows with a BTREE INDEX in Field
, I get these results:
╔═════════════╦═════════════╗
║ Operator ║ Time (secs) ║
╠═════════════╬═════════════╣
║ ~* ║ 1.5 ║
║ SIMILAR TO ║ 1.4 ║
║ ANY ARRAY ║ 4.0 ║
║ OR OR OR... ║ 4.0 ║
╚═════════════╩═════════════╝
select 'cata' ilike any (array['%cat%','%dog%','%animal%','%pet%']);
?column?
----------
t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With