How to split a column in SQL
This simple example walks you through the steps involved using a column with a First and Last name and shows you how to split these into two separate columns
2. Suppose you had a column which
you need to split into two
A typical use case is splitting Full
Name in First and Last names
3. Here are the steps to approach
splitting the column
Firstly Find the position of the
delimiter
In our case it’s a space
Charindex(' ', name) as [Space
Position]
5. Next,
Extract the characters to the left of the space
left(name,(Charindex(' ', name)-1)) as [First Name]
This takes the space position of 5 in the first example, subtracts 1 to remove the
space itself, and returns the first 4 characters
6. For the last name, we want everything to the right of the space
substring(name,(Charindex(' ', name)+1), (len(name) -Charindex(' ', name))) as
[Last Name]
This takes the space position of 5 in the first example, adds 1 to remove the
space itself, and returns the remaining characters by evaluating how many
characters remain
7. Here is the full SQL code
select name
, Charindex(' ', name) as [Space Position]
, len(name) as [Name Length]
, left(name,(Charindex(' ', name)-1)) as [First Name]
, substring(name,(Charindex(' ', name)+1), (len(name) -Charindex(' ', name)))
as [Last Name]
from [dbo].[names]
8. You can apply this same
technique to split other types
of data, or substitute the space
for a different character