You need to pull the data from the БД so that they are unique and trim them. It is necessary to trim all after the remaining character in the string - '_' (trim including the '_' character). That is, if we have the values ​​in the name field - 'Tom_1', 'Tom_2', 'Tom_Rob_3' should output - "Tom", "Tom_Rob"

 SELECT DISTINCT ON (name) FROM user 

How to do it?

    1 answer 1

     SELECT DISTINCT ON(name_trimmed) LEFT(name, length(name) - position('_' in reverse(name))) AS name_trimmed FROM "user" 

    SQL Fiddle example