LearnContact
Lesson 4220 min read

String Functions

Learn the most common built-in MySQL string functions for combining, cleaning, and transforming text data.

Introduction

Real-world data is rarely stored exactly how you want to display it. Names might be split across two columns, text might have extra spaces, or you might need to show only part of a value. MySQL provides a rich set of built-in string functions to handle exactly this kind of cleanup and transformation.

In this lesson we will use a simple "students" table to explore the most commonly used string functions: CONCAT(), UPPER(), LOWER(), LENGTH(), TRIM(), SUBSTRING(), and REPLACE().

setup.sql
CREATE TABLE students (
    id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100)
);

INSERT INTO students (id, first_name, last_name, email) VALUES
(1, 'Alex', 'Johnson', '  alex.johnson@mail.com'),
(2, 'priya', 'Sharma', 'PRIYA.SHARMA@MAIL.COM'),
(3, 'Sam', 'Lee', 'sam.lee@mail.com  ');
What You Will Learn
  • How to join text together with CONCAT().
  • How to change text case with UPPER() and LOWER().
  • How to measure text with LENGTH().
  • How to remove extra spaces with TRIM().
  • How to extract part of a string with SUBSTRING().
  • How to swap text with REPLACE().

Why String Functions Matter

String functions let you transform text data directly inside a SQL query, without pulling the data into an application first. This is useful for formatting output, cleaning messy imported data, and building derived values like a full name from separate first and last name columns.

CONCAT()

CONCAT() joins two or more strings into one. It is one of the most frequently used string functions, especially for combining columns like first_name and last_name into a single display value.

SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM students;
Result
+----------------+
| full_name      |
+----------------+
| Alex Johnson   |
| priya Sharma   |
| Sam Lee        |
+----------------+
Tip

Any literal text you place inside CONCAT(), like the single space ' ', is inserted exactly as written between the joined values.

UPPER() and LOWER()

UPPER() converts text to all uppercase, and LOWER() converts text to all lowercase. These are commonly used to standardize data for comparisons or for consistent display.

SELECT first_name, UPPER(first_name) AS upper_name, LOWER(email) AS lower_email
FROM students;
Result
+------------+------------+---------------------------+
| first_name | upper_name | lower_email               |
+------------+------------+---------------------------+
| Alex       | ALEX       |   alex.johnson@mail.com   |
| priya      | PRIYA      | priya.sharma@mail.com     |
| Sam        | SAM        | sam.lee@mail.com          |
+------------+------------+---------------------------+

LENGTH()

LENGTH() returns the number of bytes in a string (for most simple text, this equals the number of characters). It is useful for validating data or spotting unexpectedly short or long values.

SELECT first_name, LENGTH(first_name) AS name_length
FROM students;
Result
+------------+-------------+
| first_name | name_length |
+------------+-------------+
| Alex       | 4           |
| priya      | 5           |
| Sam        | 3           |
+------------+-------------+
Note

If your text contains multi-byte characters (like emoji or certain accented letters), use CHAR_LENGTH() instead to count characters rather than bytes.

TRIM()

TRIM() removes leading and trailing spaces from a string. This is extremely useful when cleaning up data that was imported from a spreadsheet or entered by a user, where stray spaces are common.

SELECT email, TRIM(email) AS cleaned_email
FROM students
WHERE id = 1;
Result
+---------------------------+-----------------------+
| email                     | cleaned_email          |
+---------------------------+-----------------------+
|   alex.johnson@mail.com   | alex.johnson@mail.com |
+---------------------------+-----------------------+

MySQL also supports LTRIM() (removes leading spaces only) and RTRIM() (removes trailing spaces only), if you only need to trim one side.

SUBSTRING()

SUBSTRING() extracts part of a string, starting at a given position for a given length. Position numbering starts at 1, not 0.

SELECT first_name, SUBSTRING(first_name, 1, 3) AS short_name
FROM students;
Result
+------------+------------+
| first_name | short_name |
+------------+------------+
| Alex       | Ale        |
| priya      | pri        |
| Sam        | Sam        |
+------------+------------+
Tip

If you omit the length argument, e.g. SUBSTRING(email, 1, LENGTH(email) - 10), SUBSTRING() returns everything from the start position to the end of the string.

REPLACE()

REPLACE() finds every occurrence of one substring inside a string and swaps it for another. It is handy for quick corrections, like fixing a wrong domain name across many email addresses.

SELECT email, REPLACE(email, '@mail.com', '@school.edu') AS new_email
FROM students;
Result
+---------------------------+-------------------------------+
| email                     | new_email                     |
+---------------------------+-------------------------------+
|   alex.johnson@mail.com   |   alex.johnson@school.edu     |
| PRIYA.SHARMA@MAIL.COM     | PRIYA.SHARMA@MAIL.COM         |
| sam.lee@mail.com          | sam.lee@school.edu            |
+---------------------------+-------------------------------+
Case Sensitivity

Notice that priya's row was not replaced, because REPLACE() is case-sensitive by default and her email uses uppercase '@MAIL.COM'. Combine REPLACE() with UPPER() or LOWER() first if you need case-insensitive matching.

Reference Table

Here is a quick reference for the string functions covered in this lesson.

FunctionPurposeExampleResult
CONCAT()Joins strings togetherCONCAT('Sam', ' ', 'Lee')Sam Lee
UPPER()Converts to uppercaseUPPER('sam')SAM
LOWER()Converts to lowercaseLOWER('SAM')sam
LENGTH()Counts bytes/charactersLENGTH('Sam')3
TRIM()Removes leading/trailing spacesTRIM(' Sam ')Sam
SUBSTRING()Extracts part of a stringSUBSTRING('Sam Lee', 1, 3)Sam
REPLACE()Swaps a substringREPLACE('Sam Lee', 'Lee', 'Kim')Sam Kim

Worked Example: Full Name

Let's combine several of these functions to build a single, clean, properly formatted full name from the messy first_name and email columns.

worked_example.sql
SELECT
    CONCAT(UPPER(SUBSTRING(first_name, 1, 1)), LOWER(SUBSTRING(first_name, 2)), ' ', last_name) AS full_name,
    TRIM(LOWER(email)) AS clean_email
FROM students;
Result
+----------------+------------------------+
| full_name      | clean_email            |
+----------------+------------------------+
| Alex Johnson   | alex.johnson@mail.com  |
| Priya Sharma   | priya.sharma@mail.com  |
| Sam Lee        | sam.lee@mail.com       |
+----------------+------------------------+

This query capitalizes only the first letter of first_name (using SUBSTRING() to split it into its first character and the rest), lowercases the remainder, joins it with last_name using CONCAT(), and separately produces a trimmed, lowercased email — all directly inside SQL.

Common Mistakes

Avoid These Mistakes
  • Forgetting that SUBSTRING() positions start at 1, not 0.
  • Assuming REPLACE() is case-insensitive when it is not.
  • Using LENGTH() on multi-byte text and expecting a character count instead of a byte count.
  • Forgetting to alias computed columns, which leaves them with unreadable auto-generated names.

Best Practices

  • Always alias computed string expressions with AS so results are readable.
  • Trim and normalize case on imported or user-entered text before comparing it.
  • Nest string functions carefully, working from the innermost function outward.
  • Test string functions on a few sample rows before applying them to an UPDATE statement.

Frequently Asked Questions

Can I use string functions in a WHERE clause?

Yes. For example, WHERE LOWER(email) = 'alex.johnson@mail.com' lets you compare in a case-insensitive way.

Does CONCAT() handle NULL values safely?

No — if any argument to CONCAT() is NULL, the entire result becomes NULL. Use CONCAT_WS() or IFNULL() if you need to handle missing values gracefully.

What is the difference between SUBSTRING() and SUBSTR()?

They are aliases for the same function in MySQL — you can use either name interchangeably.

Can these functions modify the actual stored data?

Not on their own in a SELECT. To permanently change stored data you would use them inside an UPDATE statement, which is covered in a later lesson.

Key Takeaways

  • CONCAT() joins strings together, including literal text like spaces.
  • UPPER() and LOWER() standardize text case.
  • LENGTH() measures the size of a string in bytes.
  • TRIM() removes unwanted leading and trailing spaces.
  • SUBSTRING() extracts a portion of a string by position and length.
  • REPLACE() swaps every occurrence of a substring for another, and is case-sensitive.

Summary

String functions let you clean and transform text directly inside your SQL queries, saving you from writing extra application code just to format data.

In this lesson, you learned CONCAT(), UPPER(), LOWER(), LENGTH(), TRIM(), SUBSTRING(), and REPLACE(), and combined several of them to build a clean full name. Next, you will explore MySQL's numeric functions.

Lesson 42 Completed
  • You can join, format, and clean text using built-in string functions.
  • You understand how to combine multiple string functions together.
  • You are ready to move on to numeric functions.
Next Lesson →

Numeric Functions