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
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
HINT: No operator found with given name and argument types. You may need to convert types explicitly.
4
Answers
You could cast the
code
field to text and then useLIKE
:If you have many substrings and want to avoid a lengthy
WHERE
clause, then load your substrings into a proper table:And use the following join with your original table to find matches:
You can use the SQL "LIKE" operator combined with the "OR" operator to extract the records that contain any of the specified substrings in the "code" field.
In your example:
To know more about "LIKE" operator I recommend to look at some other example here: SQL LIKE Operator
To avoid repeating the where condition for each substring, you may use a cte that contains all the substrings and then do a join with your table as the following:
demo
You can use unnest() on your array for the input an map the content using a regex: