← Back to MySQL Course | Chapter 12: String Functions | Lesson 5 of 7

TRIM LTRIM RTRIM

Introduction to TRIM

TRIM strips whitespace from both the start and end of a string while leaving any spaces in the middle untouched, which matters when comparing or storing user-typed values that often carry accidental padding.

Example: Introduction to TRIM

sql
SELECT TRIM('   Hello World   ') AS trimmed;

Using LTRIM

LTRIM removes only leading whitespace from the left edge of a string, keeping trailing spaces intact. It's useful when you specifically want to normalize how a value starts without altering anything after it.

Example: Using LTRIM

sql
SELECT LTRIM('   Hello World   ') AS left_trimmed;

Using RTRIM

RTRIM mirrors LTRIM but works on the right edge instead, stripping trailing spaces while leaving the front of the string alone. This is common when cleaning fixed-width import data that pads values with trailing blanks.

Example: Using RTRIM

sql
SELECT RTRIM('   Hello World   ') AS right_trimmed;

Cleaning Specific Characters

TRIM isn't limited to whitespace — passing the LEADING, TRAILING, or BOTH keyword lets you strip a specific character, like removing stray leading zeros or trailing commas from imported text instead of just blank space.

Example: Cleaning Specific Characters

sql
SELECT TRIM(LEADING '0' FROM '000123') AS no_leading_zeros;
SELECT TRIM(TRAILING ',' FROM 'item,item,') AS no_trailing_comma;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Form Validation and Cleaning

Form input is a classic source of stray spaces, since users often add a space before or after typing an email or username. Trimming values before saving them prevents subtle bugs where '[email protected]' and '[email protected] ' are treated as two different accounts.

Example: Form Validation and Cleaning

sql
CREATE TABLE users (id INT, email TEXT);
INSERT INTO users VALUES (1, '[email protected] '), (2, '[email protected]');
SELECT * FROM users WHERE TRIM(email) = '[email protected]';
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.