// strings reference

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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.