SQL QuestSQL Interview QuestionsString Functions

Her Own First Name

HardProQuerying BasicsString FunctionsConditional LogicNULL HandlingSubqueries & CTEs

The passenger register files most married women under their husband's name: Maioni, Mrs. Norman (Lucia) is Lucia Maioni, travelling as Mrs. Norman Maioni. When the register knows the woman's own name, it writes it in parentheses. A memorial project wants those names back.

For every passenger whose name contains Mrs. and a name in parentheses, show exactly these 4 columns, in this order:

- passenger_id
- surname — everything before the comma
- own_first_name — the first word inside the parentheses. Usually the parentheses hold one word ((Lucia)); sometimes a full name ((Mary D Kingcome)), and then only Mary is wanted
- husband_first_name — the first word between Mrs. and the opening parenthesis, or NULL when nothing is written there (Hewlett, Mrs. (Mary D Kingcome)) — NULL, not an empty string

Order by passenger_id.

Why this is Hard: nothing here sits at a fixed position. Every cut is an INSTR that finds a marker, and the length of each piece is the distance between two markers. Taking the first word needs a CASE, because INSTR(text, ' ') returns 0 when there is no space — and a SUBSTR whose length works out to -1 returns an empty string without complaint. That empty string is the last trap: it is not NULL, so a report that counts missing husbands with IS NULL would miss every one you leave behind.

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: 52 rows — e.g. 103 · Maioni · Lucia · Norman, and 16 · Hewlett · Mary · NULL

Hint

This is a Pro challenge — the hint, the step-by-step tutor and the reference solution open in the app.

Concepts

SELECT String Functions SUBSTR INSTR TRIM LIKE CASE NULLIF CTE

Practise the topic: SQL practice questions · String function practice · CASE WHEN practice · NULL handling practice · CTE practice · Advanced SQL interview questions

Read the concept: SQL cheat sheet

Related questions

Email Username Extract (SUBSTR + INSTR)Medium · FreeNames That Don't Match Their EmailMedium · FreePassenger Family Survival AnalysisHard · ProShelve the Films Library-StyleHard · ProLong-Named PassengersEasy · FreeEmployee Display Cards (Concat)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