Postgresql Contains in where clause

30,090

Solution 1

There are a bunch of ways of solving this:

  1. Use like, ilike, and/or SIMILAR TO along with ||. To handle columns, something like:

    WHERE col1 ilike '%' || col2 || '%';
    
  2. Use position as NPE's answer

  3. You could also use regexp_matches but that is more complex.

Solution 2

You could use position() for that. It returns zero if the substring is not found:

position(col2 in col1) <> 0
Share:
30,090
Gopinagh.R
Author by

Gopinagh.R

Java Developer profile for Gopinagh.R on Stack Exchange, a network of free, community-driven Q&amp;A sites http://stackexchange.com/users/flair/239490.png

Updated on April 20, 2020

Comments

  • Gopinagh.R
    Gopinagh.R about 4 years

    Is there a function in postgres like contains ? that can be used in the where clause to check , whether the string passed is contained in column?

  • vyegorov
    vyegorov about 11 years
    It is possible to use col1 ~ 'abc' or col1 ~ col2 also for this case.
  • StartupGuy
    StartupGuy about 10 years
    I find that the performance of ~ is much better than LIKE (YMMV)
  • mauhiz
    mauhiz over 9 years
    ~ is actually a REGEXP. The alias of like is ~~