1

I have a name column like this:

Name
------
Roger
RogerMan
Roger That

I need a query which would return distinct initials from the column. For example, in this case I want to return:

Name
-----
R
RM
RT

I have tried a number of approaches for this: 1. CASE statement (works perfectly by far). 2. STRCMP 3. SUBSTRING

However, I am looking for a more dynamic approach using functions in Postgres.

1
  • Garfield, in your example, you will have two rows, R and RT because RogerMan being one word will just return R as its initial. Commented Feb 12, 2020 at 16:43

1 Answer 1

3

You could use regexp_replace() to remove all non capital alphabetic characters from the string, like so:

 regexp_replace(name, '[^A-Z]', '', 'g')

Demo on DB Fiddle:

with t(name) as (
    select 'Roger'
    union all select 'RogerMan'
    union all select 'Roger That'
)
select name, regexp_replace(name, '[^A-Z]', '', 'g') initials from t
name       | initials
:--------- | :-------
Roger      | R       
RogerMan   | RM      
Roger That | RT      
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.