TExcelTAD
Home › MySQL › MySQL String Functions

MySQL String Functions

MySQL has a large library of functions for working with text. This lesson groups the most useful ones by task. Positions in MySQL strings start at 1, not 0.

Joining and changing case

Function Example Result
CONCAT(s1, s2, ...) CONCAT('My', 'SQL') MySQL (NULL if any argument is NULL)
CONCAT_WS(sep, s1, ...) CONCAT_WS('-', 'a', 'b') a-b (skips NULLs)
UPPER(s) / LOWER(s) UPPER('shop') SHOP
REPEAT(s, n) REPEAT('ab', 3) ababab
REVERSE(s) REVERSE('abc') cba
mysql · try it yourself
SELECT CONCAT(UPPER(last_name), ', ', first_name) AS directory_name,
       LOWER(CONCAT(first_name, '.', last_name, '@shop.example')) AS staff_email,
       CONCAT_WS(' / ', title, IF(manager_id IS NULL, 'top', NULL)) AS role
FROM employees
WHERE employee_id IN (1, 4);
+----------------+---------------------------+-----------+
| directory_name | staff_email               | role      |
+----------------+---------------------------+-----------+
| HOPPER, Grace  | grace.hopper@shop.example | CEO / top |
| BERG, Linus    | linus.berg@shop.example   | Sales Rep |
+----------------+---------------------------+-----------+

Length and position

Function Returns
CHAR_LENGTH(s) number of characters
LENGTH(s) number of bytes (differs for non-ASCII text)
LOCATE(sub, s) / INSTR(s, sub) position of the first sub in s (0 if absent); note the swapped argument order
LOCATE(sub, s, start) the same, searching from position start
mysql · try it yourself
SELECT email,
       CHAR_LENGTH(email) AS len,
       LOCATE('@', email) AS at_pos,
       INSTR(email, '.') AS first_dot
FROM customers
WHERE customer_id IN (1, 11);
+-------------------------+------+--------+-----------+
| email                   | len  | at_pos | first_dot |
+-------------------------+------+--------+-----------+
| ana.silva@example.com   |   21 |     10 |         4 |
| kofi.mensah@example.com |   23 |     12 |         5 |
+-------------------------+------+--------+-----------+

Extracting parts

Function Example Result
LEFT(s, n) / RIGHT(s, n) LEFT('Espresso', 3) Esp
SUBSTRING(s, pos, len) (SUBSTR, MID) SUBSTRING('Espresso', 2, 4) spre
SUBSTRING(s, -n) SUBSTRING('Espresso', -3) sso
SUBSTRING_INDEX(s, delim, n) SUBSTRING_INDEX('a.b.c', '.', 2) a.b (negative n counts from the right)

SUBSTRING_INDEX is perfect for splitting an e-mail address:

mysql · try it yourself
SELECT email,
       SUBSTRING_INDEX(email, '@', 1)  AS user_part,
       SUBSTRING_INDEX(email, '@', -1) AS domain,
       LEFT(first_name, 1) AS initial,
       SUBSTRING(last_name, 2, 3) AS middle_bit
FROM customers
WHERE customer_id IN (2, 5);
+-------------------------+-------------+-------------+---------+------------+
| email                   | user_part   | domain      | initial | middle_bit |
+-------------------------+-------------+-------------+---------+------------+
| ben.carter@example.com  | ben.carter  | example.com | B       | art        |
| elena.rossi@example.com | elena.rossi | example.com | E       | oss        |
+-------------------------+-------------+-------------+---------+------------+

Trimming, padding and replacing

Function Example Result
TRIM(s), LTRIM, RTRIM TRIM(' hi ') hi
TRIM(BOTH 'x' FROM s) TRIM(BOTH '-' FROM '--a--') a
LPAD(s, n, pad) / RPAD LPAD('7', 3, '0') 007
REPLACE(s, from, to) REPLACE('a-b-c', '-', '+') a+b+c (case-sensitive)
INSERT(s, pos, len, new) INSERT('Hello', 2, 3, 'XYZ') HXYZo
mysql · try it yourself
SELECT CONCAT('INV-', LPAD(order_id, 5, '0')) AS invoice_no,
       RPAD(status, 12, '.') AS padded_status,
       REPLACE(status, 'deliver', 'receiv') AS replaced,
       CONCAT('[', TRIM('   spaced out   '), ']') AS trimmed
FROM orders
WHERE order_id IN (3, 21);
+------------+---------------+------------+--------------+
| invoice_no | padded_status | replaced   | trimmed      |
+------------+---------------+------------+--------------+
| INV-00003  | delivered...  | received   | [spaced out] |
| INV-00021  | processing..  | processing | [spaced out] |
+------------+---------------+------------+--------------+

Formatting and searching

Function Example Result
FORMAT(x, d) FORMAT(1234567.891, 2) 1,234,567.89
FIELD(s, a, b, c) FIELD('b', 'a', 'b', 'c') 2 (position in the list, 0 if absent)
FIND_IN_SET(s, 'a,b,c') FIND_IN_SET('c', 'a,b,c') 3
STRCMP(a, b) STRCMP('apple', 'banana') -1 (0 equal, 1 greater)
REGEXP_REPLACE(s, pattern, new) replace with a regular expression
REGEXP_SUBSTR(s, pattern) the first match of a regular expression
mysql · try it yourself
SELECT FORMAT(1234567.891, 2) AS formatted,
       REGEXP_SUBSTR(name, '[0-9]+') AS first_number,
       REGEXP_REPLACE(name, '[0-9]+(kg|g|L|ml)', '') AS without_size,
       STRCMP('apple', 'banana') AS cmp
FROM products
WHERE product_id IN (1, 11);
+--------------+--------------+-----------------+-----+
| formatted    | first_number | without_size    | cmp |
+--------------+--------------+-----------------+-----+
| 1,234,567.89 | 1            | Espresso Beans  |  -1 |
| 1,234,567.89 | 500          | Greek Yogurt    |  -1 |
+--------------+--------------+-----------------+-----+

(REGEXP_REPLACE and REGEXP_SUBSTR exist since MySQL 8.0 and MariaDB 10.0.5. Their regular-expression engines differ, ICU in MySQL and PCRE in MariaDB, but simple patterns like these behave the same.)

Tip: Functions applied to a column in WHERE (WHERE UPPER(email) = ...) prevent the use of an index on that column. Since comparisons are already case-insensitive by default, you rarely need UPPER/LOWER for searching.

Test yourself

What does SUBSTRING('Database', 5, 4) return?

  1. base
  2. abas
  3. Data
  4. ase

What is SUBSTRING_INDEX('www.shop.example', '.', -2)?

  1. www.shop
  2. shop.example
  3. example
  4. www

What does LPAD('42', 5, '0') return?

  1. 42000
  2. 00042
  3. 0042
  4. 42