Data Cleaning Exercises

Reference · SQL (DuckDB)

Trim whitespace in SQL (DuckDB)

Remove a declared set of characters from both ends of a text value without touching the inside.

When to use it

Keys, codes and categories padded with spaces, tabs or line breaks, before any comparison or lookup.

How

trim(x, characters) removes the listed characters from both ends. Without a list, DuckDB removes spaces only.

trim(customer_code, ' ' || chr(9) || chr(13) || chr(10))
  • ltrim and rtrim work on one side.
  • Follow with NULLIF(..., '') when an empty result should be missing.

Pitfalls

  • Relying on the tool's default definition of whitespace.
  • Casting identifiers to numbers to drop padding.
  • Trimming only one side.

Lesson: Trim the right characters, and only those

Practise it: Clean an order-line export