How to Split a String in SQL

Have you ever wanted to split a string into separate parts in SQL? Whether you're looking to break up a list of names or parse out a complex address, SQL has you covered! Let's take a look at how to split a string in SQL.

The Solution

The solution is to use the SUBSTRING_INDEX() function. This function takes three arguments: the string you want to split, the delimiter you want to use, and the index of the substring you want to return. For example, if you wanted to split a string of names separated by commas into individual names, you would use the following query:

SELECT SUBSTRING_INDEX(string, ',', index) FROM table_name;

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called users with the following data:

users
nameage
John, Jane, Bob25
Alice, Bob30

If you wanted to split the names into individual names, you would use the following query:

SELECT SUBSTRING_INDEX(name, ',', 1) AS first_name,
SUBSTRING_INDEX(name, ',', -1) AS last_name
FROM users;

This query would return the following result:

first_namelast_name
JohnBob
AliceBob

Additional Info

The SUBSTRING_INDEX() function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database. 🤓

Want to build your own LLM Apps with AirOps👇👇