Search code examples
sqlpostgresqlregexp-replace

split text if contains certain string postgres


exit_reason

sr_inefficient_management
tech_too_complex
company_member_resignation
sr_product_engagement
sr_contractual_reasons
sr_contractual_reasons-expectation_issues
sr_churn-takeover_business

I would like to split the column if the value contains the string "sr_" and keep the rest as it is. If the column contains "-" such as "sr_contractual_reasons-expectation_issues", I only want to keep it as "contractual reasons". So far, my idea is to use

case when exit_reason like '%inefficient_management%' then 'inefficient management'

but if there are many different values, I am in trouble.

Expected output

exit_reason column

tech too complex
company member resignation
product engagement
contractual reasons
contractual reasons
churn

Solution

  • You can just replace 'sr_'

    replace(exit_reason, 'sr_', '')
    

    It is unlikely that 'sr_' would appear in any of the reasons. But you can use regexp_replace() to be sure:

    regexp_replace(exit_reason, '^sr_', '')