SQL truncate with ellipsis
The display-truncation pattern: cut to N characters and append ... when the value was longer. Simple until emoji and combining marks join.
- 类别
- Strings
- Returns
string- In this category
- 74 of 172
语法
CASE WHEN LEN(s) > 40 THEN LEFT(s, 37) + '...' ELSE s END
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
示例
SQL Server
SELECT CASE WHEN LEN(title) > 40 THEN LEFT(title, 37) + '...' ELSE title END AS short FROM posts;
PostgreSQL
SELECT CASE WHEN length(title) > 40 THEN left(title, 37) || '...' ELSE title END AS short FROM posts;
值得了解
- Count the ellipsis inside the budget: cutting to 37 and appending '...' yields 40 characters total. Decide which number your spec means.
- Multibyte width: under a non-SC collation SQL Server's LEN and LEFT count UTF-16 code units, so an emoji is 2 units and a cut can split it in half. PostgreSQL and SQLite count code points.
- Cutting mid-word looks broken; cutting on the last space before the limit reads better but costs a second CHARINDEX/position call.
- The single ellipsis character … (U+2026) is one character but three bytes in UTF-8, so byte-limited columns (SQL Server varchar, Oracle VARCHAR2 by default) count it as 3.
Questions about Truncating with an ellipsis
Why is my truncated string 40 characters but too wide?
Characters are not display width: emoji, CJK and combining marks render wider or narrower than they count. Character-based truncation approximates visual width only.
Can truncation split an emoji in half?
Yes on SQL Server under a non-SC collation: SUBSTRING and LEFT count code units, so a boundary can fall between surrogate halves. A supplementary-character collation (_SC, _140) makes them count whole characters.
Should I truncate in SQL or the app?
SQL is fine for fixed-width feeds and previews; the app has better tools for word-aware truncation and locale text. Keep the rule in one place either way.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.