Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a string with multiple characters into seperate columns in SQL?

I have a table which looks like this:

Cust_ID Customer_Group Company City Country
1927373 Microsoft – Liverpool – United Kingdom
1928373 Google – Mumbai – India

I’m trying to figure out how to get seperate the dashes to get different values into different columns. So the first word before the first dash (‘-‘) would populate the ‘Company’ column. I would also like to get the word after the first dash and populate that into the ‘City’ column. Finally, I would also like to get the last part of the string after the second dash to populate that into my ‘Country’ column.

So the goal is to have the table updated like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cust_ID Customer_Group Company City Country
1927373 Microsoft – Liverpool – United Kingdom Microsoft Liverpool United Kingdom
1928373 Google-Mumbai-India Google Mumbai India

Is this possible? Some of the values in the Customer_Group field either have a white space or no white pace before and after the dash (‘-‘) character but I was also hoping to remove the white space that may appear before the word when it is inserted into the new columns.

>Solution :

Using INSTR(), SUBSTR and TRIM

UPDATE your_table
SET Company = TRIM(SUBSTR(Customer_Group, 1, INSTR(Customer_Group, '-') - 1)),
    City = TRIM(SUBSTR(Customer_Group, INSTR(Customer_Group, '-') + 1, INSTR(Customer_Group, '-', INSTR(Customer_Group, '-') + 1) - INSTR(Customer_Group, '-') - 1)),
    Country = TRIM(SUBSTR(Customer_Group, INSTR(Customer_Group, '-', INSTR(Customer_Group, '-') + 1) + 1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading