SQL: Extract a string from between the 2nd and 3rd dashes (-), if they exist. Else N/A

Viewed 29

How to write SQL to extract the string from the 2nd and 3rd dashes on the "Campaign" column to a new column "Language".

If no 2nd and 3rd dashes, then "N/A". Thank you for your help!

Campaign Language
na--en-abc en
na-branded N/A
ap--jp-xyz jp
eu-uk-en-jjj en
1 Answers

Consider below simple approach

select Campaign,
  ifnull(split(Campaign, '-')[safe_offset(2)], 'N/A') as Language
from your_table

If applied to sample data in your question - output is

enter image description here

Related