Data Engineering

Handling Hidden Spaces: TRIM, LTRIM, RTRIM

SQL Mastery Team
April 9, 2026
4 min read

Welcome to **Day 78**. Today we're fixing the most invisible bug in SQL: **Whitespace**.

The Problem

A user signs up and accidentally hits the spacebar at the end of their username: `"bob "`.

Later, they try to log in as `"bob"`.

To the database, these are NOT the same. Your query `WHERE username = 'bob'` will return nothing, and the user will get a "Password Incorrect" error.

The Solution: TRIM()

`TRIM()` removes spaces from both the beginning and the end of a string.

SELECT * FROM users

WHERE TRIM(username) = 'bob';

Variations

  • **LTRIM()**: Only removes spaces from the **Left** (beginning).
  • **RTRIM()**: Only removes spaces from the **Right** (end).
  • Pro Tip: Indexing

    Be careful! Using `TRIM(column)` in your `WHERE` clause can prevent the database from using an index on that column. It's better to `TRIM` the data **before** it gets saved to the database.

    If it's already messy, you might need a **Function-Based Index**.

    Your Task for Today

    Run `SELECT username FROM users WHERE username LIKE '% %'` to see if anyone has accidental spaces in their names.

    *Day 79: CAST vs TO_DATE—Fixing String Dates.*

    Ready to put your knowledge into practice?

    Join SQL Mastery and learn through interactive exercises.