regexpostgresqlsql-function

Check if variable contains x in PostgreSQL function


In a PostgreSQL function, what is the syntax to check if a variable passed in contains a specific letter?

The variable being passed to the function is comma separated list of letters and I want to check if this list contains the letter a or x.

I imagine the code would look something like this:

-- var typically looks like 'a,b,c,x'
if (some way of stripping anything other than a and x from var) ~* [ax]
  -- Do something else
end if;

I assume regex is the answer, I'm just not 100% sure about the syntax.

Thanks!


Solution

  • The easiest way to check if a string contains a substring or a letter is

    if ( var like '%x%')
      -- Do something else
    end if;
    

    Or you can use regexp as you mentioned:

    if ( var ~* 'x')