MySQL String Functions - Complete Tutorial
Quick Answer
MySQL string functions allow you to manipulate and query text data efficiently. Functions like CONCAT, SUBSTRING, LENGTH, and REPLACE help perform operations such as concatenation, extraction, length calculation, and substitution within strings.
Learning Objectives
- Understand the purpose and usage of common MySQL string functions.
- Learn how to manipulate text data using functions like CONCAT, SUBSTRING, and REPLACE.
- Apply string functions in practical SQL queries to solve real-world problems.
Introduction to MySQL String Functions
Working with text data is a common task in database management. MySQL offers a variety of string functions to help you manipulate and analyze string values efficiently.
These functions enable you to concatenate strings, extract substrings, find string lengths, replace parts of strings, and more, making your SQL queries more powerful and flexible.
Text data is everywhere, and mastering string functions is key to unlocking its potential.
Common MySQL String Functions
MySQL includes many built-in functions to work with strings. Below are some of the most commonly used ones that every developer should know.
- CONCAT(): Concatenates two or more strings into one.
- SUBSTRING(): Extracts a substring from a string starting at a specified position.
- LENGTH(): Returns the length of a string in bytes.
- CHAR_LENGTH(): Returns the length of a string in characters.
- REPLACE(): Replaces occurrences of a substring within a string with another substring.
- LOWER() and UPPER(): Convert strings to lowercase or uppercase.
- TRIM(): Removes leading and trailing spaces from a string.
CONCAT() Function
The CONCAT() function is used to join two or more strings into a single string. It is very useful when you want to combine columns or add text to existing data.
- Syntax: CONCAT(string1, string2, ...)
- Returns NULL if any argument is NULL.
SUBSTRING() Function
SUBSTRING() extracts a portion of a string starting from a specified position for a given length. It helps when you need to isolate parts of a string.
- Syntax: SUBSTRING(string, start_position, length)
Practical Examples of String Functions
Let's look at some practical examples to see how these string functions work in real SQL queries.
Concatenating First and Last Names
You can combine first and last name columns into a full name using CONCAT().
Extracting Area Code from Phone Number
Use SUBSTRING() to extract the area code from a phone number string.
Practical Example
This query combines the first_name and last_name columns with a space in between to create a full_name.
This extracts the first three characters from the phone_number column, typically representing the area code.
This replaces all occurrences of 'old-domain.com' with 'new-domain.com' in the email column.
Examples
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;This query combines the first_name and last_name columns with a space in between to create a full_name.
SELECT SUBSTRING(phone_number, 1, 3) AS area_code FROM contacts;This extracts the first three characters from the phone_number column, typically representing the area code.
SELECT REPLACE(email, 'old-domain.com', 'new-domain.com') AS updated_email FROM users;This replaces all occurrences of 'old-domain.com' with 'new-domain.com' in the email column.
Best Practices
- Always check for NULL values when using string functions to avoid unexpected NULL results.
- Use CHAR_LENGTH() instead of LENGTH() when working with multi-byte character sets.
- Combine string functions to perform complex text manipulations efficiently.
- Test string functions with sample data to ensure expected behavior.
Common Mistakes
- Using LENGTH() to count characters in multi-byte strings, leading to incorrect results.
- Not handling NULL inputs, causing entire expressions to return NULL.
- Forgetting that CONCAT() returns NULL if any argument is NULL.
- Misusing SUBSTRING() start positions (MySQL strings are 1-indexed).
Hands-on Exercise
Use SUBSTRING() to Extract Domain
Write a query to extract the domain part from an email address (after the '@' symbol).
Expected output: A column showing the domain part of email addresses.
Hint: Use SUBSTRING_INDEX() or locate the '@' position with LOCATE() and then SUBSTRING().
Replace Spaces with Underscores
Write a query to replace all spaces in a product name with underscores.
Expected output: Product names with spaces replaced by underscores.
Hint: Use the REPLACE() function.
Interview Questions
What does the CONCAT() function do in MySQL?
InterviewCONCAT() joins two or more strings into a single string. If any argument is NULL, the result is NULL.
How do LENGTH() and CHAR_LENGTH() differ?
InterviewLENGTH() returns the length of a string in bytes, while CHAR_LENGTH() returns the number of characters, which is important for multi-byte characters.
What happens if you use CONCAT() with a NULL argument?
InterviewThe result of CONCAT() will be NULL if any argument is NULL.
MCQ Quiz
1. What is the best first step when learning String Functions?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce String Functions?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. MySQL string functions allow you to manipulate and query text data efficiently.
B. String Functions never needs examples
C. String Functions is unrelated to practical work
D. String Functions should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- MySQL provides a rich set of string functions for text manipulation.
- Functions like CONCAT and SUBSTRING are essential for combining and extracting parts of strings.
- Using string functions effectively can simplify complex SQL queries involving text data.
- MySQL string functions allow you to manipulate and query text data efficiently.
- Functions like CONCAT, SUBSTRING, LENGTH, and REPLACE help perform operations such as concatenation, extraction, length calculation, and substitution within strings.
Summary
MySQL string functions are essential tools for manipulating text data within your databases.
Functions like CONCAT, SUBSTRING, LENGTH, and REPLACE allow you to combine, extract, measure, and modify strings effectively.
Mastering these functions will help you write more powerful and flexible SQL queries.
Frequently Asked Questions
Can CONCAT() handle more than two strings?
Yes, CONCAT() can take two or more string arguments and concatenate them all into one string.
What is the difference between LENGTH() and CHAR_LENGTH()?
LENGTH() returns the number of bytes in a string, while CHAR_LENGTH() returns the number of characters, which is important for multi-byte character sets.
How do I remove leading and trailing spaces from a string?
Use the TRIM() function to remove leading and trailing spaces from a string.





