1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL String Functions Explained: TRIM, SUBSTR, REPLACE, CONCAT and Data Cleanup

Real-world text is messy: extra spaces, mixed case, phone numbers with brackets and missing surnames. SQL string functions clean and reshape that text inside the database. We ran each one against deliberately messy customer data.

11 min read
SQL string functions explained: TRIM, SUBSTR, REPLACE, CONCAT and data cleanup

Key takeaways

  • SQL string functions trim, change case, extract, replace and join text inside queries.
  • In standard SQL, concatenating with NULL gives NULL. Use COALESCE or CONCAT_WS.
  • Untidy text splits groups: “pune”, “Pune ” and “PUNE” are three different cities until cleaned.
  • Function names differ across databases, so check the dialect cheat sheet before porting queries.

A report counts customers by city and shows “pune: 1” and “Pune : 1” as separate rows. A mailing list has emails with capital letters and trailing spaces, so duplicates slip through. A full-name column is blank for anyone without a surname. All three problems are solved with SQL string functions, the everyday tools for cleaning and shaping text.

We ran every query in SQLite 3.50, and the results are from that run. Most functions exist in every database, sometimes with different names, listed in the cheat sheet below.

The messy sample data

CREATE TABLE customers (id INTEGER PRIMARY KEY, first TEXT, last TEXT,
                        email TEXT, phone TEXT, city TEXT);
INSERT INTO customers (first, last, email, phone, city) VALUES
 ('  Asha ', 'Rao',  'Asha.Rao@Example.com ', '+91 98765-43210',  'pune'),
 ('Ben',     NULL,   'ben@example.com',       '(022) 2345 6789',  'MUMBAI'),
 ('Chitra',  'Iyer', 'chitra@shop.co.in',     '9876543210',       'Pune ');

Extra spaces, inconsistent capitals, a missing surname and three different phone formats: a fairly typical import from a web form or spreadsheet.

Concatenation and the NULL trap

SELECT first || ' ' || last FROM customers;
-- '  Asha  Rao', NULL, 'Chitra Iyer'

Two problems at once. Asha’s name kept its stray spaces, and Ben’s full name disappeared entirely, because in standard SQL anything concatenated with NULL becomes NULL. Two fixes:

SELECT trim(first) || COALESCE(' ' || last, '') FROM customers;
-- 'Asha Rao', 'Ben', 'Chitra Iyer'

SELECT concat_ws(' ', trim(first), last) FROM customers;
-- 'Asha Rao', 'Ben', 'Chitra Iyer'

COALESCE replaces the NULL piece with an empty string, putting the space inside the optional part so Ben does not get a trailing space. CONCAT_WS, “concatenate with separator”, skips NULLs automatically and is available in SQLite 3.44 and later, MySQL, PostgreSQL and SQL Server 2017+. Note that MySQL’s plain CONCAT() returns NULL if any argument is NULL, while PostgreSQL’s and SQL Server’s CONCAT() treat NULL as empty. Our guide to NULL values covers more of these surprises.

TRIM and LENGTH

SELECT first, length(first), length(trim(first)) FROM customers WHERE id = 1;
-- '  Asha ', 7, 4

Three invisible characters were hiding in “Asha”. TRIM removes leading and trailing spaces; LTRIM and RTRIM remove one side only. SQLite and several other databases let you name the characters to remove, such as trim(code, '.-'). Note that TRIM does not remove spaces in the middle; that is a job for REPLACE. Tabs and non-breaking spaces copied from web pages are also not removed by a plain TRIM in most databases, a common reason “cleaned” values still do not match.

UPPER and LOWER

SELECT lower(trim(email)) FROM customers;
-- 'asha.rao@example.com', 'ben@example.com', 'chitra@shop.co.in'

SELECT upper(substr(trim(city), 1, 1)) || lower(substr(trim(city), 2)) FROM customers;
-- 'Pune', 'Mumbai', 'Pune'

Normalising emails to lower case and trimming them is the standard first step before checking for duplicates or joining tables. The second query capitalises the first letter of each city, a simple title case for single words. One catch: SQLite’s built-in lower() only changes ASCII letters. lower('ÇAFÉ') returned 'ÇafÉ', leaving the accented capitals untouched. Other databases handle Unicode case better, depending on collation and settings.

SUBSTR and INSTR

SELECT substr(email, instr(email, '@') + 1) FROM customers;
-- 'Example.com ', 'example.com', 'shop.co.in'

SELECT substr('INV-2026-0042', -4);
-- '0042'

INSTR finds the position of the “@”, and SUBSTR takes everything after it, extracting the email domain. Positions start at 1, not 0. A negative start counts from the end, which neatly pulls the last part of a code. The first result shows why order matters: we extracted from the raw email, so the domain kept its capital and trailing space. Clean first, then extract. PostgreSQL uses position() or strpos(), MySQL has LOCATE, and SQL Server uses CHARINDEX and SUBSTRING.

REPLACE

SELECT replace(replace(replace(replace(replace(phone,' ',''),'-',''),'(',''),')',''),'+','')
FROM customers;
-- '919876543210', '02223456789', '9876543210'

Nested REPLACE calls stripped spaces, hyphens, brackets and plus signs, leaving digits only. It works, but it is clumsy, and the results still differ: one number has a country code, one has an area code, and one has neither. Text functions can tidy a format, but they cannot work out what a number means. For that, normalise numbers in the application with a proper library, or in databases with regular expression functions such as PostgreSQL’s regexp_replace; see our Python regex guide for the patterns.

Tip: Before running an UPDATE that cleans data, run the same expression in a SELECT next to the original column and check a sample, just as we did above. String functions are easy to get slightly wrong, and an UPDATE replaces the only copy.

Why cleaning matters for GROUP BY

SELECT city, COUNT(*) FROM customers GROUP BY city;
-- ('MUMBAI', 1), ('Pune ', 1), ('pune', 1)

SELECT lower(trim(city)) AS c, COUNT(*) FROM customers GROUP BY c;
-- ('mumbai', 1), ('pune', 2)

The raw query reported three cities with one customer each. Cleaned, Pune correctly has two. The same problem affects joins, DISTINCT counts and duplicate detection, which is why dirty text produces silently wrong reports. Our GROUP BY guide shows more aggregation patterns.

Padding and formatting

SELECT printf('INV-%05d', 42);   -- 'INV-00042'

Zero-padding produces fixed-width codes that sort correctly as text. SQLite uses printf (also named format); PostgreSQL and MySQL offer LPAD and RPAD, as in LPAD('42', 5, '0'); SQL Server uses FORMAT or RIGHT('00000' + value, 5). Formatting for display is often better left to the application, but padded identifiers are worth generating consistently in one place.

Unicode and length

SELECT length('नमस्ते'), length(CAST('नमस्ते' AS BLOB));
-- 6, 18

The Hindi greeting is 6 characters but 18 bytes in UTF-8. Character counts matter for validation, such as “name at most 50 characters”, while byte counts matter for storage limits and some column types. MySQL’s LENGTH returns bytes and CHAR_LENGTH returns characters; SQL Server’s LEN also ignores trailing spaces. Knowing which one you are using prevents odd truncation bugs with non-English text.

Dialect cheat sheet

Task SQLite PostgreSQL MySQL SQL Server
Join text ||, concat_ws ||, CONCAT CONCAT, CONCAT_WS +, CONCAT
Substring substr substring, substr SUBSTRING SUBSTRING
Find position instr strpos LOCATE, INSTR CHARINDEX
Length length length CHAR_LENGTH LEN
Pad printf lpad LPAD FORMAT
Regex replace Extension only regexp_replace REGEXP_REPLACE REGEXP_REPLACE (2025)

The SQLite column was tested; the others are from each database’s documentation and were not run for this article.

Performance

Wrapping a column in a function, as in WHERE lower(email) = ?, usually prevents a normal index from being used, so the database scans every row. Options include storing a cleaned copy of the value, adding an index on the expression where supported (PostgreSQL, SQLite and MySQL 8 support expression indexes), or using a case-insensitive collation. The same principle applies to date functions, as we showed in SQL date functions.

Clean on the way in

String functions in queries are a repair tool. The lasting fix is to clean data when it is saved: trim and normalise case in the application or a trigger, validate formats with CHECK constraints, and store phone numbers in one canonical format. Then reports stay simple, indexes work, and duplicates are caught at the door.

A cleanup recipe

When you inherit a table of messy text, a predictable order of operations avoids most mistakes:

  1. Measure the mess: count distinct raw values and compare them with lower(trim(...)) versions to see how many duplicates hide in formatting.
  2. Trim first, then normalise case, because spaces and capitals affect every later step.
  3. Extract or replace parts, such as domains or digits, only from the cleaned value.
  4. Handle NULLs explicitly with COALESCE or CONCAT_WS wherever values are combined.
  5. Preview the result beside the original in a SELECT, and review a sample by eye.
  6. Update inside a transaction, check row counts, then commit, as covered in SQL transactions.
  7. Stop the mess returning with validation, constraints or a trigger on insert.

Following the same steps every time makes cleanups reviewable and repeatable, instead of a series of one-off fixes.

Final thoughts

A handful of functions, TRIM, LOWER, SUBSTR, INSTR, REPLACE and CONCAT, handle most text cleanup in SQL. Watch for NULL in concatenation, hidden spaces, ASCII-only case conversion and character-versus-byte lengths. Preview every cleanup in a SELECT before an UPDATE, and move the cleaning upstream so tomorrow’s data arrives tidy.

Frequently asked questions

Why does my concatenated string return NULL?

In standard SQL, joining any value with NULL gives NULL. Use COALESCE around nullable parts or CONCAT_WS, which skips NULLs.

How do I remove spaces in SQL?

TRIM removes leading and trailing spaces. To remove spaces inside a value, use REPLACE(column, ‘ ‘, ”).

What is the difference between SUBSTR and SUBSTRING?

They do the same job; the name depends on the database. SQLite uses substr, SQL Server uses SUBSTRING, and PostgreSQL and MySQL accept both forms.

How do I extract the domain from an email in SQL?

Find the @ with INSTR or a similar function, then take the substring after it, after trimming and lower-casing the email.

Do string functions slow down queries?

Using them on a column in WHERE can stop an index being used. Use an expression index, a cleaned column or a suitable collation instead.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Databases & SQL

SQL String Functions Explained: TRIM, SUBSTR, REPLACE, CONCAT and Data Cleanup

SQL string functions explained with queries we ran: concatenation and NULL, TRIM, UPPER and LOWER, SUBSTR and INSTR, REPLACE, padding,…

Read article →
Databases & SQL

SQL Triggers Explained: BEFORE and AFTER Triggers, Audit Logs and Pitfalls

SQL triggers explained with triggers we ran: BEFORE vs AFTER, OLD and NEW, audit logs, validation, stock updates, WHEN conditions,…

Read article →
Software Development

Python JSON Module Explained: dumps, loads, Custom Types and Common Errors

The Python JSON module explained with code we ran: dumps and loads, files, type conversions, dates and decimals, custom encoders,…

Read article →
Software Development

ES Modules vs CommonJS: How JavaScript Imports Work in Node.js, Tested

ES modules vs CommonJS explained with code we ran in Node.js: import and export syntax, require, live bindings, caching, top-level…

Read article →
Software Development

Python Regex Explained: Patterns, Groups, Lookaheads and Pitfalls, Tested

Python regex explained with patterns we ran: search vs match, findall, groups and named groups, greedy vs lazy, sub, lookaheads,…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →