// SQL snippet

Find values truncated at the max length

Compare each value's length against the column limit and list the rows pinned at the ceiling, where silent truncation leaves its mark.

Main statement
PostgreSQL
También cubre
SQL Server

The task

products.name is VARCHAR(50) and old loaders cut overflow silently. Values measuring exactly 50 characters are the ones to re-check against the source feed.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
SELECT id, name, LENGTH(name) AS name_length
FROM products
WHERE LENGTH(name) = 50
ORDER BY name_length DESC, id;

Cómo funciona

LENGTH(name) measures each value in characters; the predicate keeps only values exactly at the column's declared limit. A value that hits the ceiling exactly is rarely a coincidence. It is usually the visible stump of a longer source string. Repeat with each width-limited column.

Variations

SQL Server: DATALENGTH (bytes, trailing spaces included)

SQL Server
SELECT id, name, DATALENGTH(name) AS name_bytes
FROM products
WHERE DATALENGTH(name) = 50
ORDER BY id;

Look up each text column's limit (PostgreSQL information_schema)

PostgreSQL
SELECT c.column_name, c.character_maximum_length
FROM information_schema.columns c
WHERE c.table_name = 'products'
  AND c.data_type = 'character varying'
ORDER BY c.ordinal_position;

Questions that come up

Why characters and not bytes?

Because PostgreSQL declares VARCHAR(50) in characters, and so does MySQL. Measure the same unit the limit uses: LENGTH on PostgreSQL and SQLite, CHAR_LENGTH on MySQL (its LENGTH counts bytes). The other two differ: Oracle's VARCHAR2(50) means 50 bytes unless declared with CHAR semantics, so use LENGTHB there, and SQL Server's VARCHAR(50) is 50 bytes, so use DATALENGTH, which unlike LEN also counts trailing spaces.

Keep reading

// snippets are better with a schema brain

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.