Ellipsize long text with a trailing ellipsis in SQL
Fixed-width UI slots need a hard cap, and the dots tell readers the text continues.
The task
Cap the preview at 120 characters and add three dots only when something was actually removed.
The snippet
Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.
SELECT CASE WHEN LEN(blurb) > 120
THEN LEFT(blurb, 117) + '...'
ELSE blurb END AS preview
FROM articles;
工作原理
The CASE checks the full length first. Long values keep 117 characters, and the three dots bring the display total back to exactly 120. LEN ignores trailing spaces on SQL Server, which is usually harmless for prose but matters if your strings can be all-spaces.
Variations
PostgreSQL
PostgreSQLSELECT CASE WHEN length(blurb) > 120
THEN left(blurb, 117) || '...'
ELSE blurb END AS preview
FROM articles;
MySQL
MySQLSELECT CASE WHEN CHAR_LENGTH(blurb) > 120
THEN CONCAT(LEFT(blurb, 117), '...')
ELSE blurb END AS preview
FROM articles;
Questions that come up
Can I combine this with word-boundary truncation?
Yes: replace LEFT(blurb, 117) with the word-boundary expression limited to 117 characters. That gives previews that never cut a word and never exceed the cap.
Keep reading
Related on SQLly
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.