Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting strings in SQLite

Tags:

sql

split

sqlite

How do I split my address columns into three new columns separated by its commas?

1808  FOX CHASE DR, GOODLETTSVILLE, TN

Divided into:

  • 1808 FOX CHASE DR
  • GOODLETTSVILLE
  • TN

I've tried:

SELECT
    SUBSTRING(OwnerAddress, 1, INSTR(OwnerAddress, ',')-1) as col1,
    SUBSTRING(OwnerAddress, INSTR(OwnerAddress, ',')+1) as col2  
FROM housing_data;

I cannot create the third column with the state abbreviation.

like image 598
Alastair Thomson Avatar asked Mar 11 '26 22:03

Alastair Thomson


1 Answers

It's generally much cleaner to do any sort of string processing in the target library. That said, if you must, you can make liberal use of SUBSTRING and INSTR to find each comma and split the strings:

SELECT 
    SUBSTRING(OwnerAddress, 1, INSTR(OwnerAddress, ',') - 1) as col1,
    SUBSTRING(SUBSTRING(OwnerAddress, INSTR(OwnerAddress, ',') + 1), 1, INSTR(SUBSTRING(OwnerAddress, INSTR(OwnerAddress, ',') + 1), ',') - 1) as col2,
    SUBSTRING(SUBSTRING(OwnerAddress, INSTR(OwnerAddress, ',') + 1), INSTR(SUBSTRING(OwnerAddress, INSTR(OwnerAddress, ',') + 1), ',') + 1) as col3
FROM housing_data;
like image 166
Anon Coward Avatar answered Mar 13 '26 12:03

Anon Coward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!