SQL Quest › SQL Interview Questions › String Functions
Her Own First Name
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_id | survived | pclass | name | sex | age | sibsp | parch | fare | embarked |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22 | 1 | 0 | 7.25 | S |
| 2 | 1 | 1 | Cumings, Mrs. John Bradley | female | 38 | 1 | 0 | 71.28 | C |
| 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26 | 0 | 0 | 7.93 | S |
Expected output: 52 rows — e.g. 103 · Maioni · Lucia · Norman, and 16 · Hewlett · Mary · NULL
Hint
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
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