SQL QuestSQL Interview Questions › String Functions

Extract Family Names (SUBSTR + INSTR)

EasyFreeQuerying BasicsString Functions

The passenger registry stores names as 'LastName, Mr. FirstName' (last name before the comma, honorific and first name after). For a demographics view, extract just the last name part.

Show passenger_id, name, and SUBSTR(name, 1, INSTR(name, ',') - 1) AS last_name. Order by passenger_id. Limit to 15 rows.

INSTR(haystack, needle) returns the 1-indexed position of the first match (or 0 if not found). SUBSTR(string, start, length) extracts a substring. Combine them when you need a piece of a string up to (or after) a delimiter — this is the classic "split on comma" pattern in engines that don't have a SPLIT_PART function.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

passengers

passenger_idsurvivedpclassnamesexagesibspparchfareembarked
103Braund, Mr. Owen Harrismale22107.25S
211Cumings, Mrs. John Bradleyfemale381071.28C
313Heikkinen, Miss. Lainafemale26007.93S

Expected output: last_name = 'Braund'

Hint

INSTR returns the position of ','. Subtract 1 because you want everything BEFORE the comma. SUBSTR starts counting at position 1 (not 0).

Concepts

SELECT SUBSTR INSTR String Functions

Practise the topic: SQL practice questions · String function practice

Related questions

Long-Named PassengersEasy · FreeEmployee Display Cards (Concat)Easy · FreeCountry Codes in UppercaseEasy · FreeYear Code from Order Date (SUBSTR)Easy · FreeMovie Title Initial Letter Histogram (SUBSTR)Easy · FreePosition of '@' in Email (INSTR)Easy · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test