Between the Spaces

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L3
Asked in
Google

Problem

Return each message's ID and its word count from chat_msgs, for an analyst profiling how wordy the chat is who treats every space in the content as a divider between words.

Every pause between words is a vote for length. Count them.

Tables

chat_msgs

Columns: msg_id INTEGER, channel TEXT, sender_id INTEGER, content TEXT, msg_type TEXT, sent_at TEXT, edited INTEGER, reply_to INTEGER

chat_msgs: 10 of 200 rows
msg_idchannelsender_idcontentmsg_typesent_ateditedreply_to
147#engineering197Anyone seeing increased latency?file2026-02-02 01:07:000NULL
194#incidents294PR #412 ready for reviewreaction2026-03-03 02:14:000NULL
241#random391Dashboard is downthread_reply2026-04-04 03:21:000NULL
288#deployments488Fixed the flaky testsystem2026-05-05 04:28:000NULL
335#data-team585Merged the migrationText2026-06-06 05:35:000NULL
382#general682NULLFILE2026-07-07 06:42:000NULL
429#engineering779LGTMtext2026-08-08 07:49:000NULL
476#incidents876👍file2026-09-09 08:56:0005
523#random973reaction2026-01-10 09:03:000NULL
570#deployments1070Can someone check the pipeline?thread_reply2026-02-11 10:10:000NULL

Expected output

First 5 of 200 rows
msg_idword_count
1474
1945
2413
382NULL
4291

Worked solution and explanation

The trick hiding under a metric

Strip the costume and this is counting one character. Anyone can measure a string; the skill is turning the spaces in content into words, and the cheapest way is to measure how much the string shrinks when the spaces are stripped out. The real trap is the plus one and the nulls. Forget the plus one and every count is off by a word: 'Dashboard is down' has two spaces and three words. Forget that a missing body makes LENGTH return NULL, or paper over it with a default, and you invent a number where the honest answer is unknown.


Break down the requirements

Step 1: Turn spaces into a word count

Words are separated by spaces, so the number of words is the number of spaces plus one. Count the spaces by measuring how many characters vanish when you strip them: LENGTH(content) - LENGTH(REPLACE(content, ' ', '')) is the space count, and adding 1 turns dividers into words.

Step 2: Return message ID and word count

Select msg_id next to the computed expression aliased as word_count. Because NULL content flows through LENGTH untouched, those rows come back as NULL for free, which is exactly what the expected output shows.


The solution

Space-counting word count
SELECT
    msg_id,
    LENGTH(content) - LENGTH(REPLACE(content, ' ', '')) + 1 AS word_count
FROM chat_msgs

Common follow-up questions