Mastering MySQL for Data AnalystsLesson 34 of 42
Lesson 34 of 42

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 StringMySQL Cleaning FunctionClean Standardized ResultBusiness Benefit
rahul.s@GMAIL.COM LOWER(TRIM(email))rahul.s@gmail.comDeduplicates customer accounts
+91-987-654-3210REPLACE(REPLACE(phone, '-', ''), '+91', '')9876543210Uniform 10-digit mobile number
Indiranagar, , 560038CONCAT_WS(', ', street, landmark, pincode)Indiranagar, 560038CONCAT_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:

Feature 1

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.

Syntax / Code Pattern:
SELECT CONCAT_WS(" ", first_name, middle_name, last_name) AS full_name FROM customers;
Parameters Breakdown:
  • separator: In CONCAT_WS, the delimiter string inserted between arguments.
  • str1, str2...: String expressions to concatenate.
Real-World Example (Customer Address Formatting):
Problem / Scenario: Build a formatted street address skipping missing apartment numbers.
SQL Query / Expression: CONCAT_WS(', ', street, apt_no, city, state, pincode)
Result: '12th Main Road, Indiranagar, Bengaluru, KA, 560038'
Why it works: CONCAT_WS ignores apt_no if it is NULL without introducing double commas.
Feature 2

SUBSTRING() / SUBSTR() / MID()

Definition: Extracts a substring starting at a 1-based index position for an optional length count.

Syntax / Code Pattern:
SELECT SUBSTRING(order_code, 1, 3) AS prefix, SUBSTRING(order_code, 5) AS id FROM orders;
Parameters Breakdown:
  • str: Source string.
  • pos: 1-based starting character position (negative counts from end).
  • len: Number of characters to extract.
Real-World Example (Store Code Extraction from Order ID):
Problem / Scenario: Extract the 3-letter store code from order identifier "BLR-98421".
SQL Query / Expression: SUBSTRING('BLR-98421', 1, 3)
Result: 'BLR'
Why it works: Extracts 3 characters starting at character index 1.
Feature 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).

Syntax / Code Pattern:
SELECT LENGTH("Ice Cream ") AS bytes, CHAR_LENGTH("Ice Cream ") AS chars;
Parameters Breakdown:
  • str: Input string expression.
Real-World Example (Unicode SMS Length Verification):
Problem / Scenario: Verify promotional SMS text length where emoji characters consume 4 bytes each.
SQL Query / Expression: CHAR_LENGTH(promo_text)
Result: 14 characters (while LENGTH() is 17 bytes)
Why it works: CHAR_LENGTH accurately measures human-visible character length.
Feature 4

TRIM(), LTRIM() & RTRIM()

Definition: Removes leading and/or trailing whitespace or specified prefix/suffix characters from strings.

Syntax / Code Pattern:
SELECT TRIM(BOTH " " FROM user_input), TRIM(LEADING "0" FROM serial_no);
Parameters Breakdown:
  • remstr: Optional character to remove (defaults to space).
Real-World Example (Form Input Sanitization):
Problem / Scenario: Clean accidental leading and trailing whitespace entered by users in email input fields.
SQL Query / Expression: TRIM(LOWER(input_email))
Result: ' user@scoopcraft.in ' -> 'user@scoopcraft.in'
Why it works: Strips whitespace padding and normalizes case for reliable lookup.
Feature 5

REPLACE(str, from_str, to_str)

Definition: Replaces all occurrences of from_str with to_str in a case-sensitive manner.

Syntax / Code Pattern:
SELECT REPLACE(phone, "+91-", "") AS clean_mobile FROM users;
Parameters Breakdown:
  • str: Target string.
  • from_str: Substring to search for.
  • to_str: Replacement string.
Real-World Example (Phone Number Normalization):
Problem / Scenario: Strip dashes and spaces from customer mobile numbers.
SQL Query / Expression: REPLACE(REPLACE(phone, '-', ''), ' ', '')
Result: '987-654 3210' -> '9876543210'
Why it works: Chained replace eliminates formatting noise for database deduplication.

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)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + 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").