← Back to Chapters

MySQL String Functions

? MySQL String Functions

? Quick Overview

MySQL provides a rich set of string functions that allow you to manipulate, search, and format textual data stored in databases. These functions are widely used for data cleaning, reporting, and transforming user input.

? Key Concepts

  • String concatenation and formatting
  • Extracting specific parts of text
  • Changing letter case
  • Removing unwanted spaces
  • Searching and replacing substrings

? Syntax / Theory

MySQL string functions operate on character-based data types such as CHAR, VARCHAR, and TEXT. Most functions accept one or more string arguments and return a modified string or numeric result.

? Code Examples

? View Code Example
// Concatenate multiple strings into one
SELECT CONCAT('Hello', ' ', 'World') AS greeting;
? View Code Example
// Extract first five characters from a string
SELECT SUBSTRING('Hello World', 1, 5) AS sub_string;
? View Code Example
// Count total characters in a string
SELECT LENGTH('Hello World') AS string_length;
? View Code Example
// Convert text to uppercase
SELECT UPPER('hello world') AS upper_case;
? View Code Example
// Remove leading and trailing spaces
SELECT TRIM('  Hello World  ') AS trimmed_string;
? View Code Example
// Replace part of a string with new text
SELECT REPLACE('Hello World', 'World', 'MySQL') AS replaced_string;

? Live Output / Explanation

Each query returns a transformed version of the input string. For example, CONCAT() joins strings together, while SUBSTRING() extracts only a selected portion of text.

? Interactive Concept

You can combine multiple string functions in a single query to build advanced transformations, such as cleaning user input before storing it in a database.

? Use Cases

  • Formatting names and addresses
  • Cleaning imported CSV data
  • Generating readable reports
  • Normalizing text for comparison

✅ Tips & Best Practices

  • Use CONCAT_WS() to safely join strings with separators.
  • Apply TRIM() before comparisons to avoid hidden spaces.
  • Combine multiple string functions for powerful transformations.

? Try It Yourself

  • Combine UPPER() and TRIM() in one query.
  • Create a query that extracts initials from a full name.
  • Experiment with LEFT() and RIGHT() functions.