In MySQL, section 9.4 of the reference manual covers string functions and operators—built-in routines that manipulate character data, such as concatenating, searching, extracting, and formatting text. These functions work on strings (CHAR, VARCHAR, TEXT) and return string or numeric results, forming the backbone of data cleaning, reporting, and application logic in SQL queries.
What Are String Functions and Operators?
String functions are SQL commands that take one or more string inputs and return a transformed string, a number, or a boolean. Operators like LIKE, REGEXP, and the concatenation operator || (in some modes) are also part of this section. They are essential for tasks like:
- Formatting names or addresses for display
- Searching for patterns within text
- Extracting substrings for analysis
- Comparing strings case-insensitively
- Cleaning up data with inconsistent whitespace or case
For example, a simple query using CONCAT and UPPER might be: SELECT UPPER(CONCAT(first_name, ' ', last_name)) AS full_name FROM users;
Core String Functions You’ll Use Daily
MySQL provides dozens of string functions. The most frequently used ones include:
CONCAT(str1, str2, ...)– joins strings; returns NULL if any argument is NULL. UseCONCAT_WSwith a separator.LENGTH(str)– returns the length in bytes (for multi-byte characters, useCHAR_LENGTH).SUBSTRING(str, pos, len)– extracts a substring starting at positionpos(1-based).REPLACE(str, from, to)– replaces all occurrences offromwithto.TRIM([remstr FROM] str)– removes leading/trailing spaces or specified characters.UPPER(str)andLOWER(str)– convert case.LEFT(str, n)andRIGHT(str, n)– return the leftmost/rightmost n characters.
These functions are deterministic—given the same input, they always return the same output—which makes them safe for indexing (in some cases) and for use in generated columns.
String Comparison and Pattern Matching Operators
Beyond functions, operators allow you to compare and match strings:
=and<>– exact equality (case-insensitive by default collation).LIKE– pattern matching with%(any sequence) and_(single character).REGEXP(orRLIKE) – regular expression matching (POSIX extended syntax).STRCMP(str1, str2)– returns 0 if equal, -1 if first is smaller, 1 if larger (based on collation).
Example: SELECT * FROM products WHERE name LIKE 'iPhone%'; finds products starting with “iPhone”. For case-sensitive matching, use a case-sensitive collation or the BINARY keyword.
How to Choose the Right Function
Selecting the correct function depends on your goal:
- If you need to join multiple columns, use
CONCATorCONCAT_WS(the latter ignores NULLs). - If you need to extract a fixed-length portion, use
LEFT,RIGHT, orSUBSTRINGwith a length. - If you need to find a position, use
LOCATE(substr, str)orINSTR(str, substr). - If you need to replace text,
REPLACEis simplest, but for regex-based replacement, useREGEXP_REPLACE(MySQL 8.0+).
Always test with your actual data, especially when using SUBSTRING with multi-byte characters—use CHAR_LENGTH and SUBSTRING with character positions, not byte positions.
Common Pitfalls and Misconceptions
Several issues trip up new users:
- NULL propagation: Most string functions return NULL if any argument is NULL. For example,
CONCAT('a', NULL)returns NULL, not ‘a’. UseIFNULLorCOALESCE. - Byte vs. character length:
LENGTH()returns bytes; for UTF-8 strings with accented characters, it differs fromCHAR_LENGTH(). Always useCHAR_LENGTHfor user-facing text. - Case sensitivity: Default collations (like
utf8mb4_0900_ai_ci) are case-insensitive. To force case-sensitive comparison, useBINARYor a collation ending in_cs. - LIKE vs. REGEXP:
LIKEis faster but less powerful;REGEXPsupports complex patterns but is slower. UseLIKEfor simple wildcard searches.
A common misconception is that SUBSTRING is 0-based—it is 1-based in MySQL. So SUBSTRING('hello', 1, 2) returns ‘he’, not ‘el’.
Performance and Indexing Considerations
Using string functions in WHERE clauses can prevent index usage. For example, WHERE UPPER(name) = 'JOHN' will not use an index on name. To optimize:
- Store data in a consistent case (e.g., lowercase) and query with the same case.
- Use generated columns for pre-computed values (e.g.,
name_lower) and index those. - For prefix searches, use
LIKE 'abc%'which can use an index, but avoid leading wildcards like'%abc'. - For full-text search, consider
FULLTEXTindexes instead ofLIKEfor large text columns.
For example, to find users by last name case-insensitively, create a generated column: ALTER TABLE users ADD last_name_lower VARCHAR(255) AS (LOWER(last_name)) STORED; then index it.
String Functions in Different SQL Dialects
MySQL’s string functions are similar but not identical to other databases:
- In PostgreSQL, concatenation uses
||(which MySQL also supports ifPIPES_AS_CONCATSQL mode is enabled), andLENGTHreturns characters, not bytes. - In SQL Server, you use
LEN(excludes trailing spaces) andCHARINDEXinstead ofLOCATE. - In Oracle,
CONCATonly takes two arguments, andSUBSTRis 1-based but treats NULLs differently.
When migrating, be aware of these differences to avoid subtle bugs.
Frequently Asked Questions
Q: What is the difference between CHAR_LENGTH and LENGTH?
CHAR_LENGTH returns the number of characters, while LENGTH returns the number of bytes. In a UTF-8 column, ‘é’ is 1 character but 2 bytes. Use CHAR_LENGTH for readability and LENGTH for storage size.
Q: How do I concatenate strings with a separator, ignoring NULLs?
Use CONCAT_WS(separator, str1, str2, ...). For example, CONCAT_WS(', ', 'John', NULL, 'Doe') returns ‘John, Doe’.
Q: Can I use string functions in a WHERE clause?
Yes, but be aware of performance. Functions like UPPER(name) prevent index usage. Consider storing normalized data or using generated columns.
Q: How do I extract the domain from an email address?
Use SUBSTRING(email, LOCATE('@', email) + 1). For example, SUBSTRING('user@example.com', LOCATE('@', 'user@example.com') + 1) returns ‘example.com’.
Q: Why does CONCAT return NULL when one argument is NULL?
That’s SQL standard behavior. Use COALESCE or IFNULL to replace NULLs before concatenation, e.g., CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, '')).
Q: Is there a function to reverse a string?
Yes, REVERSE(str) returns the string reversed. For example, REVERSE('abc') returns ‘cba’.
Related
- How to Use split() Method in Java
- Color by Number Hot Air Balloon: How It Works
- Split s2 in SQL? How to Split a String
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Create a Unique Signature in OutlookTo create a unique signature in Outlook, open the signature editor for your version, write a concise sign-off…
- Approximate Match Lookup in Excel: Formulas and TipsFor a numeric approximate lookup in Excel, use an ascending threshold table and a formula that returns the…
- Excel Filter Shortcut: Alt Keys and Faster OptionsIn Excel for Microsoft 365 on Windows, press Alt, then A, then T to apply or remove AutoFilter;…
- SUMIF Example Formula: Syntax, Uses, and Common FixesWith product names in A2:A7 and sales amounts in B2:B7, use =SUMIF(A2:A7,"Apples",B2:B7) to add the sales for Apples;…
- AVERAGEIF in Excel: How It Works and When to Use ItAVERAGEIF in Excel calculates the average of numbers that meet one condition. Give it a range to check,…
- Excel Formula for Loan Payment Calculation: PMT ExplainedThe Excel formula for loan payment calculation is =PMT(rate, nper, pv), where rate is the periodic interest rate,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.