SoFunction
Updated on 2025-04-08

PostgreSQL uses various methods to determine whether a string contains a target string

Several methods for PostgreSQL to determine the content of strings:

Method 1: position(substring in string):

position(substring in string) function: Parameter 1: target string, parameter 2 original string. If the target string is included, it will return the position where the target string appears for the first time. You can judge whether the target string is included based on whether the return value is greater than 0.

select position('aa' in 'abcd');
 position 
----------
    0
select position('ab' in 'abcd');
 position 
----------
    1
select position('ab' in 'abcdab');
 position 
----------
    1

Method 2: strpos(string, substring)

strpos(string, substring) function: parameter 1: original string, target string, declared substring position, function consistent with position function.

select position('abcd','aa');
 position 
----------
    0

select position('abcd','ab');
 position 
----------
    1

select position('abcdab','ab');
 position 
----------
    1

Method 3: Use regular expressions

If the target string is included, return t, return f is not included

select 'abcd' ~ 'aa' as result;
result
------
  f 
   
select 'abcd' ~ 'ab' as result;
result
------
  t 
   
select 'abcdab' ~ 'ab' as result;
result
------
  t 

Method 4: Use the @> operator of the array (cannot accurately determine whether it contains it)

select regexp_split_to_array('abcd','') @> array['b','e'] as result;
result
------
 f

select regexp_split_to_array('abcd','') @> array['a','b'] as result;
result
------
 t

Note the following examples:

select regexp_split_to_array('abcd','') @> array['a','a'] as result;
result
----------
 t

select regexp_split_to_array('abcd','') @> array['a','c'] as result;
result
----------
 t

select regexp_split_to_array('abcd','') @> array['a','c','a','c'] as result;
result
----------
 t

It can be seen that when judging the operator containing the array, regardless of order or repetition, it will return true as long as it is included, and pay attention to it when it is actually used.

This is the article about PostgreSQL judging whether a string contains a target string. For more related PostgreSQL judging string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!