Counting the number of occurrences of a substring within a string in PostgreSQL

后端 未结 5 989
南旧
南旧 2020-12-03 09:49

How can I count the number of occurrences of a substring within a string in PostgreSQL?


Example:

I have a table

CREATE TABLE test.\"use         


        
5条回答
  •  不思量自难忘°
    2020-12-03 10:24

    A Postgres'y way of doing this converts the string to an array and counts the length of the array (and then subtracts 1):

    select array_length(string_to_array(name, 'o'), 1) - 1
    

    Note that this works with longer substrings as well.

    Hence:

    update test."user"
        set result = array_length(string_to_array(name, 'o'), 1) - 1;
    

提交回复
热议问题