Truncate text on a word boundary in SQL
List previews that cut mid-word look broken. Find the last full space before the limit and cut there.
The task
A 120-character preview that ends 'the introduct' looks broken. Cut at the last space inside the first 120 characters instead.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT CASE WHEN length(blurb) <= 120 THEN blurb
ELSE left(blurb, COALESCE(121 - NULLIF(strpos(reverse(left(blurb, 121)), ' '), 0), 120))
END AS preview
FROM articles;
Как это работает
Text that already fits comes back unchanged. Otherwise left(blurb, 121) takes one character past the limit, so a word that ends exactly at character 120 counts as complete; reverse flips it so strpos finds the last space, and the outer left cuts just before that space. When there is no space at all, NULLIF and COALESCE fall back to a hard cut at 120. Add a suffix with the ellipsize recipe if you want trailing dots.
Variations
SQL Server
SQL ServerSELECT CASE WHEN LEN(blurb) <= 120 THEN blurb
ELSE LEFT(blurb, COALESCE(121 - NULLIF(CHARINDEX(' ', REVERSE(LEFT(blurb, 121))), 0), 120))
END AS preview
FROM articles;
Questions that come up
What if the text is shorter than the limit?
The CASE returns it unchanged. Without that guard, the shorter one-liner left(blurb, 120 - strpos(reverse(left(blurb, 120)), ' ')) cuts short text too: a 111-character string whose last space sits at position 11 comes back as 19 characters.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.