SQL Functions · Lesson 7 of 30
SQL String Functions
Real data is messy: names in mixed case, extra spaces, emails you need to split, codes that need padding. SQL has built-in functions to clean and format text right in the query, so reports and exports come out right without extra code. This lesson covers the string functions you'll use most, using MySQL syntax (with notes for other databases).
In this lesson
- Joining text:
CONCATandCONCAT_WS - Case and length:
UPPER,LOWER,LENGTH,CHAR_LENGTH - Extracting:
SUBSTRING,LEFT,RIGHT,SUBSTRING_INDEX,LOCATE - Cleaning:
TRIM,REPLACE,LPAD
Joining text
SELECT CONCAT(name, ' (', city, ')') AS label,
CONCAT_WS(' | ', name, email, city) AS card
FROM customers
WHERE customer_id IN (1, 7);
+-------------------+--------------------------------------+ | label | card | +-------------------+--------------------------------------+ | Asha Verma (Pune) | Asha Verma | asha@example.com | Pune | | NULL | Neha Gupta | neha@example.com | +-------------------+--------------------------------------+
NULL swallows CONCAT
Neha's city is NULL, so CONCAT(...) returned NULL for the whole label. CONCAT_WS ("with separator") simply skips NULL values. In PostgreSQL and standard SQL you can also write name || ' ' || city (in MySQL, || means OR by default).
Case and length
SELECT name,
UPPER(name) AS upper_name,
LOWER(email) AS email,
CHAR_LENGTH(name) AS letters
FROM customers
WHERE customer_id <= 3;
+------------+------------+-------------------+---------+ | name | upper_name | email | letters | +------------+------------+-------------------+---------+ | Asha Verma | ASHA VERMA | asha@example.com | 10 | | Ravi Kumar | RAVI KUMAR | ravi@example.com | 10 | | Meera Nair | MEERA NAIR | meera@example.com | 10 | +------------+------------+-------------------+---------+
CHAR_LENGTH counts characters; LENGTH counts bytes. They differ for non-English text and symbols: "₹" is one character but three bytes in UTF-8.
SELECT CHAR_LENGTH('₹500') AS chars, LENGTH('₹500') AS bytes;
+-------+-------+ | chars | bytes | +-------+-------+ | 4 | 6 | +-------+-------+
Extracting parts of text
SELECT email,
SUBSTRING_INDEX(email, '@', 1) AS username,
SUBSTRING_INDEX(email, '@', -1) AS domain,
LEFT(name, 1) AS initial,
SUBSTRING(name, LOCATE(' ', name) + 1) AS surname
FROM customers
WHERE customer_id IN (2, 4, 6);
+-------------------+----------+-------------+---------+---------+ | email | username | domain | initial | surname | +-------------------+----------+-------------+---------+---------+ | ravi@example.com | ravi | example.com | R | Kumar | | kiran@example.com | kiran | example.com | K | Rao | | arjun@example.com | arjun | example.com | A | Singh | +-------------------+----------+-------------+---------+---------+
| Function | Returns |
|---|---|
SUBSTRING(s, start, len) | part of s; positions start at 1, not 0 |
LEFT(s, n) / RIGHT(s, n) | first / last n characters |
LOCATE(sub, s) | position of sub in s, 0 if missing (POSITION/STRPOS/CHARINDEX elsewhere) |
SUBSTRING_INDEX(s, delim, n) | text before the n-th delimiter (negative n: after, from the right) – MySQL only |
Cleaning text
SELECT CONCAT('[', TRIM(' Asha Verma '), ']') AS trimmed,
REPLACE('Clean-Code-2nd-Edition', '-', ' ') AS spaced,
LPAD(42, 6, '0') AS invoice_no,
CONCAT('ORD-', LPAD(order_id, 5, '0')) AS order_code
FROM orders
WHERE order_id = 101;
+--------------+------------------------+------------+------------+ | trimmed | spaced | invoice_no | order_code | +--------------+------------------------+------------+------------+ | [Asha Verma] | Clean Code 2nd Edition | 000042 | ORD-00101 | +--------------+------------------------+------------+------------+
A practical clean-up: masking emails
SELECT name,
CONCAT(LEFT(email, 2), REPEAT('*', LOCATE('@', email) - 3), SUBSTRING(email, LOCATE('@', email))) AS masked_email
FROM customers
WHERE customer_id IN (1, 6, 8);
+-------------+--------------------+ | name | masked_email | +-------------+--------------------+ | Asha Verma | as**@example.com | | Arjun Singh | ar***@example.com | | Vikram Das | vi****@example.com | +-------------+--------------------+
Searching with REGEXP
For patterns LIKE can't express, MySQL 8 supports regular expressions:
SELECT name FROM products WHERE name REGEXP '[0-9]'; -- names containing a digit
SELECT REGEXP_REPLACE('Call 98765-43210 now', '[^0-9]', '') AS digits_only;
+-------------------+ | name | +-------------------+ | SQL in 10 Minutes | | A5 Notebook | +-------------------+ +-------------+ | digits_only | +-------------+ | 9876543210 | +-------------+
Functions in WHERE and indexes
WHERE UPPER(email) = 'ASHA@EXAMPLE.COM' works, but wrapping a column in a function stops MySQL from using an index on it, so the whole table is scanned. Store data clean (e.g. lower-case emails on insert) and compare the plain column.
Practice
Try it yourself
Show each employee as "Surname, Firstname" in upper case, for the HR department.
Show solution
SELECT UPPER(CONCAT(SUBSTRING_INDEX(name, ' ', -1), ', ', SUBSTRING_INDEX(name, ' ', 1))) AS formatted FROM employees WHERE department = 'HR';+---------------+ | formatted | +---------------+ | REDDY, KAVYA | | SHAIKH, IMRAN | +---------------+
Show the three products with the longest names and their length in characters.
Show solution
SELECT name, CHAR_LENGTH(name) AS characters FROM products ORDER BY characters DESC LIMIT 3;+---------------------+------------+ | name | characters | +---------------------+------------+ | Mechanical Keyboard | 19 | | SQL in 10 Minutes | 17 | | JavaScript Guide | 16 | +---------------------+------------+
Quick check
What does CONCAT('a', NULL) return?
NULL – use CONCAT_WS or COALESCE to avoid it.
Do SQL string positions start at 0 or 1?
At 1.
LENGTH vs CHAR_LENGTH?
LENGTH counts bytes; CHAR_LENGTH counts characters.
Summary
- CONCAT joins text (NULL makes it NULL); CONCAT_WS skips NULLs.
- SUBSTRING, LEFT, RIGHT, LOCATE and SUBSTRING_INDEX extract parts – positions start at 1.
- TRIM, REPLACE, LPAD and REGEXP_REPLACE clean data; avoid functions on indexed columns in WHERE.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.