String Functions in MySQL: CONCAT, CONCAT_WS, SUBSTRING, LENGTH, TRIM & REPLACE
Overview & Learning Objectives
Raw data arrives messy: full names crammed into single fields, phone numbers padded with accidental whitespace, and addresses mixing hyphens and commas. Data analysts clean and standardize string fields using MySQL's rich text functions. Essential tools include `CONCAT` and `CONCAT_WS` (safe concatenation with separators), `SUBSTRING` for extracting code tokens, `TRIM` for stripping spaces, and `CHAR_LENGTH` for measuring Unicode characters.
- Sanitize dirty user inputs using `TRIM()`, `LTRIM()`, and `RTRIM()`.
- Concatenate text safely without NULL contamination using `CONCAT_WS()`.
- Extract structured tokens using `SUBSTRING()` and calculate byte vs character sizes.
Industry Standard
Standard: Analytics pipelines at Swiggy and Zomato standardize customer phone numbers and names into uniform E.164 formats using MySQL string manipulation before CRM sync.
Real-World Example: ScoopCraft Customer Profile Data Sanitization
ScoopCraft cleans raw delivery receipt logs containing whitespace padding, unformatted phone numbers, and mixed case names.
| Raw Dirty String | MySQL Cleaning Function | Clean Standardized Result | Business Benefit |
|---|---|---|---|
| rahul.s@GMAIL.COM | LOWER(TRIM(email)) | rahul.s@gmail.com | Deduplicates customer accounts |
| +91-987-654-3210 | REPLACE(REPLACE(phone, '-', ''), '+91', '') | 9876543210 | Uniform 10-digit mobile number |
| Indiranagar, , 560038 | CONCAT_WS(', ', street, landmark, pincode) | Indiranagar, 560038 | CONCAT_WS skips missing landmark cleanly |
Functions & Syntax Covered in this Chapter
Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:
CONCAT() & CONCAT_WS()
Definition: CONCAT merges strings together (returns NULL if any arg is NULL). CONCAT_WS (With Separator) uses the first argument as separator and skips NULLs.
SELECT CONCAT_WS(" ", first_name, middle_name, last_name) AS full_name FROM customers;
separator: In CONCAT_WS, the delimiter string inserted between arguments.str1, str2...: String expressions to concatenate.
CONCAT_WS(', ', street, apt_no, city, state, pincode)SUBSTRING() / SUBSTR() / MID()
Definition: Extracts a substring starting at a 1-based index position for an optional length count.
SELECT SUBSTRING(order_code, 1, 3) AS prefix, SUBSTRING(order_code, 5) AS id FROM orders;
str: Source string.pos: 1-based starting character position (negative counts from end).len: Number of characters to extract.
SUBSTRING('BLR-98421', 1, 3)LENGTH() vs CHAR_LENGTH()
Definition: LENGTH() returns byte size; CHAR_LENGTH() returns character count. Essential for multi-byte Unicode strings (e.g. emojis or regional scripts).
SELECT LENGTH("Ice Cream ") AS bytes, CHAR_LENGTH("Ice Cream ") AS chars;
str: Input string expression.
CHAR_LENGTH(promo_text)TRIM(), LTRIM() & RTRIM()
Definition: Removes leading and/or trailing whitespace or specified prefix/suffix characters from strings.
SELECT TRIM(BOTH " " FROM user_input), TRIM(LEADING "0" FROM serial_no);
remstr: Optional character to remove (defaults to space).
TRIM(LOWER(input_email))REPLACE(str, from_str, to_str)
Definition: Replaces all occurrences of from_str with to_str in a case-sensitive manner.
SELECT REPLACE(phone, "+91-", "") AS clean_mobile FROM users;
str: Target string.from_str: Substring to search for.to_str: Replacement string.
REPLACE(REPLACE(phone, '-', ''), ' ', '')Common Mistakes & Limitations
- Using `LENGTH()` instead of `CHAR_LENGTH()` to validate character limits on text containing Unicode accents or emojis (e.g. "" is 4 bytes).
- Using `CONCAT()` when columns may have NULL values, accidentally wiping out valid text.
Keyboard Shortcuts (MySQL Workbench)
| Action | Windows | Mac |
|---|---|---|
| Execute Query | Ctrl + Enter | Cmd + Enter |
Pro Tips & Modern Best Practices
- Always prefer `CONCAT_WS(" ", first, middle, last)` over `CONCAT` to avoid accidental `NULL` result bugs.
- Use `LPAD(id, 6, "0")` to format integer IDs into uniform padded codes (e.g. 42 becomes "000042").