Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

postgres. How to check if a field contains at least one substring form a list of substings?

I have a table like this

 one | two | three   |  code   | four 

-----+-------+-------+---------+--------

   0 | 21750 | 10110 | 1016916 |   20.0

   0 | 21750 | 10111 | 1017949 |   20.2 

   0 | 21750 | 10115 | 101792 |   21.0 

   0 | 21737 | 10110 | 100753 |   20.0  

   0 | 21737 | 10110 | 14343054 |   20.0 

I want to extract all records in which the field code contains at least one of the following substrings:

794, 43, 17

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do it?

UPDATE

I know I could achieve this by writing

select * from mytable where
code ilike '%794%' or
code ilike '%43%' or
code ilike '%17%';

but imagine that in the true case the matching substrings are given to my with the shape of an array ( e.g. ('794', '43', '17') ) which would have length > 100, so I don’t want to rewrite this array into 100+ WHERE conditions, each one for each substring to be searched in the code field.

I have tryed with

select * from mytable where code && '{"794", "43", "17"}';

but it throws this error

enter image description here

HINT: No operator found with given name and argument types. You may need to convert types explicitly.

>Solution :

You can use unnest() on your array for the input an map the content using a regex:

SELECT mytable.* 
FROM mytable
    JOIN unnest('{"794", "43", "17"}'::text[]) AS list(content) 
        ON code ~ content; -- regex
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading