SQL query to match one of multiple strings

牧云@^-^@ 提交于 2019-12-04 02:58:05

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 subscriberfields
where  name like any(array['%Khairpur%','%Islamabad%','%Karachi%']);

https://postgres.cz/wiki/PostgreSQL_SQL_Tricks#LIKE_to_list_of_patterns

Use OR in WHERE clause, like,

select * from subscriberfields where name like '%Khairpur%' OR name like '%Islamabad%' OR name like '%Karachi%';

Hope it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!