SQL query to match one of multiple strings
For a proper solution, either normalize your database design or, barring that, consider full text search.
For a quick solution to the problem at hand, use a regular expression match (~
) or three simple LIKE
expressions:
SELECT *FROM subscriberfields WHERE name ~ '(Khairpur|Islamabad|Karachi)';
Or:
...WHERE (name LIKE '%Khairpur%' OR name LIKE '%Islamabad%' OR name LIKE '%Karachi%')
Or use ~*
or ILIKE
for case-insensitive matching.
Since another answer suggested it: never use SIMILAR TO
:
Try using SIMILAR TO
like below:
SELECT * FROM subscriberfields WHERE name SIMILAR TO '%(Khairpur|Islamabad|Karachi)%';
Also you should read up on database normalization. Your design could and should definitely be improved.
You can use this:
select * from subscriberfieldswhere name like any(array['%Khairpur%','%Islamabad%','%Karachi%']);
https://postgres.cz/wiki/PostgreSQL_SQL_Tricks#LIKE_to_list_of_patterns