MySQL TRIM() Function
MySQL TRIM() Function
The TRIM() function strips unwanted spaces or a specified prefix/suffix substring from the start, end, or both sides of a string. By default, calling TRIM(str) removes leading and trailing ASCII spaces.
Syntax
TRIM(str)
TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)
TRIM([remstr FROM] str)
- BOTH | LEADING | TRAILING: Direction to strip (
BOTHis default). - remstr: Optional exact substring to strip (defaults to
' '). - str: Input string or column.
- Return value: Cleaned string, or
NULLifstrorremstrisNULL.
Unlike LTRIM() and RTRIM(), TRIM() lets you remove custom characters such as leading zeros from SKUs or trailing slashes from URLs.
Practical Example
Suppose demo_products contains padded product names and zero-padded SKU strings like '000482'. You can strip both outer spaces and leading zeros cleanly.
SELECT
product_id,
CONCAT('[', TRIM(product_name), ']') AS clean_name,
TRIM(LEADING '0' FROM sku) AS unpadded_sku,
TRIM(TRAILING '/' FROM '/catalog/audio/') AS clean_path
FROM demo_products
ORDER BY product_id;
| product_id | clean_name | unpadded_sku | clean_path |
|---|---|---|---|
| 1 | [USB-C Hub] | 482 | /catalog/audio |
| 2 | [Desk Lamp] | 9010 | /catalog/audio |
| 3 | [NULL] | NULL | /catalog/audio |
Notice in row 2 that LEADING '0' leaves the trailing '0' in '9010' untouched, whereas BOTH '0' would strip it too.
Common Mistakes & NULL Behavior
- remstr matches an exact substring, NOT a character set: Unlike Python
.strip('xy')or PHPtrim($s, 'xy'), MySQL'sTRIM('xy' FROM 'yxhello')does not strip'yx'—it only removes exact repeats of'xy'. - Default TRIM() ignores tabs and newlines:
TRIM(str)removes' '(ASCII32) only;,, andremain intact. - SQLite syntax difference: SQLite writes
TRIM(str, '0')with a comma, whereas MySQL usesTRIM('0' FROM str)with theFROMkeyword. - NULL propagation: If either
strorremstrisNULL,TRIM()returnsNULL.
Frequently Asked Questions
How do I strip leading and trailing tabs or newlines in MySQL?
Use REGEXP_REPLACE(str, '^[[:space:]]+|[[:space:]]+$', '') in MySQL 8.0+ to target all whitespace characters.
What happens if I omit BOTH/LEADING/TRAILING when specifying remstr?
MySQL defaults to BOTH, so TRIM('0' FROM '00420') returns '42'.
Can TRIM() remove spaces between words?
No. TRIM() only acts on the outer edges of a string; use REPLACE() or REGEXP_REPLACE() for internal whitespace.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.