# Trim Search Terms Left

> Leading whitespace. Clean it up.

Canonical URL: <https://datadriven.io/problems/trim_search_terms_left>

Domain: SQL · Difficulty: easy · Seniority: L3

## Problem

A data quality check flagged leading whitespace in some search terms. Return a cleaned-up list showing each search term with the leading spaces stripped, by query ID.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests basic string function knowledge. Interviewers use data quality cleanup scenarios to check that you know `LTRIM` and distinguish it from `TRIM` and `RTRIM`.

---

### Break down the requirements

#### Step 1: Apply LTRIM to strip leading spaces

`LTRIM(search_term)` removes leading whitespace from each search term.

#### Step 2: Return by query ID

Select `query_id` and the cleaned search term.

---

### The solution

**LTRIM for leading whitespace cleanup**

```sql
SELECT query_id, LTRIM(search_term) AS search_term
FROM search_queries
```

> **Cost Analysis**
>
> Full scan of 40M rows. LTRIM is O(k) per string where k is the number of leading spaces. This is trivially fast for typical search terms.

> **Interviewers Watch For**
>
> Using `TRIM` when the prompt only asks for leading spaces. If trailing spaces are meaningful (e.g., in pattern matching), over-trimming could alter results.

> **Common Pitfall**
>
> Assuming all whitespace is spaces. Tab characters or unicode whitespace may not be handled by `LTRIM` in all SQL dialects.

---

## Common follow-up questions

- How would you find all search terms that have leading whitespace? _(Filter WHERE search_term != LTRIM(search_term).)_
- What if you needed to normalize both leading and trailing whitespace? _(Use TRIM(search_term) instead of LTRIM.)_
- How would you also collapse multiple internal spaces to one? _(Tests REPLACE or REGEXP_REPLACE for internal whitespace normalization.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/trim_search_terms_left)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.