Split a full name into first and last name in SQL
A single full_name column has to feed a first_name / last_name pair, at least for the common two-part case.
The task
The table stores one full_name column but the mail-merge template needs first and last names. Split on the space.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT
split_part(full_name, ' ', 1) AS first_name,
CASE WHEN position(' ' IN full_name) > 0
THEN substring(full_name FROM position(' ' IN full_name) + 1)
ELSE NULL END AS last_name
FROM customers;
Fonctionnement
split_part grabs the text before the first space for the first name. For the last name the CASE guards single-word names, and substring takes everything after the first space, so 'Ann Marie Smith' keeps 'Marie Smith' as the last name rather than losing a middle name.
Variations
SQL Server
SQL ServerSELECT
LEFT(full_name, CHARINDEX(' ', full_name + ' ') - 1) AS first_name,
CASE WHEN CHARINDEX(' ', full_name) > 0
THEN SUBSTRING(full_name, CHARINDEX(' ', full_name) + 1, LEN(full_name))
ELSE NULL END AS last_name
FROM customers;
MySQL
MySQLSELECT
SUBSTRING_INDEX(full_name, ' ', 1) AS first_name,
CASE WHEN full_name LIKE '% %'
THEN SUBSTRING_INDEX(full_name, ' ', -1) ELSE NULL END AS last_name
FROM customers;
Questions that come up
How do middle names fit in?
The first space defines the split: everything after it stays together as the last name. That preserves middle names in the last-name field; the MySQL variant instead returns only the final word, so 'Ann Marie Smith' gives 'Smith' and the middle name is lost. Decide which behaviour you want; neither handles 'Juan de la Cruz' correctly.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.