← Back to SQL, page 8

sql-0148 · Medium mid

Split a full name column into first name and last name, assuming the first space separates them.

First name is SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) and last name is SUBSTR(full_name, INSTR(full_name, ' ') + 1). Handle names without a space with CASE, because INSTR returns 0 there. Real names vary a lot, so store given and family names separately when possible.

Full answer
sql
WITH people(full_name) AS (VALUES ('Asha Rao'), ('Mei'), ('Ana María López'))
SELECT full_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN full_name
            ELSE SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) END AS first_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN NULL
            ELSE SUBSTR(full_name, INSTR(full_name, ' ') + 1) END AS last_name
FROM people
ORDER BY full_name;
full_namefirst_namelast_name
Ana María LópezAnaMaría López
Asha RaoAshaRao
MeiMeiNULL

Mei has no space. INSTR returns 0, so the plain SUBSTR expression would give an empty first name. The CASE keeps the whole value as the first name and leaves the last name NULL.

Ana María López shows the limit of the rule: everything after the first space is treated as the last name. Some cultures put the family name first, and many people have several given or family names. A rule-based split is fine for a one-off clean-up, but for new data, collect the parts separately.

PostgreSQL's SPLIT_PART(full_name, ' ', 1) gives the first word directly.

sql
WITH people(full_name) AS (VALUES ('Asha Rao'), ('Mei'), ('Ana María López'))
SELECT full_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN full_name
            ELSE SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) END AS first_name,
       CASE WHEN INSTR(full_name, ' ') = 0 THEN NULL
            ELSE SUBSTR(full_name, INSTR(full_name, ' ') + 1) END AS last_name
FROM people
ORDER BY full_name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INSTR finds the first space
  • SUBSTR before and after that position gives the two parts
  • Guard the no-space case, where INSTR returns 0
  • Name structure varies across cultures

Common mistakes

  • Producing empty strings for single-word names
  • Assuming every name has exactly two parts

Follow-ups

  • How would you take the last word as the surname instead?
  • How would you design a person table for a global audience?

Tips

  • Raise the global-names point after the query