Search code examples
sqlpostgresqlrails-postgresql

SQL Count digits in a string


I have a table of the following information.

description: adjkfa34kj34kj33j4k3jk4
description: adfkjjkdf34_3434kjkjkj3
description: akjdfkjadfkjadkjfkjadfj
description: 34394394093040930949039

How would I edit the SQL query below to count the number of digits (i.e. [0-9]) in the strings?

select description as num_count
from posts;

Solution

  • One method is to get rid of all the other characters:

    select length(regexp_replace(description, '[^0-9]', '', 'g'))