SQL String Functions
Chapter 30 of 40 · Estimated read time: 10 min
Real-world data is messy — extra spaces, inconsistent casing, mixed formats. SQL string functions let you clean, transform, and extract text directly inside a query without touching the raw data. This chapter covers the functions used in almost every data analyst job.
UPPER(s)
Convert to uppercase
LOWER(s)
Convert to lowercase
LENGTH(s)
Count characters
TRIM(s)
Remove leading/trailing spaces
LTRIM(s)
Remove leading spaces only
RTRIM(s)
Remove trailing spaces only
CONCAT(a,b,...)
Join strings together
SUBSTRING(s,p,n)
Extract part of a string
REPLACE(s,old,new)
Swap one substring for another
INSTR(s,sub)
Find position of a substring
LEFT(s,n)
First n characters
RIGHT(s,n)
Last n characters
UPPER and LOWER — Normalise Case
Use these when comparing text that might have inconsistent casing, or to standardise output.
SELECT customer_name, UPPER(customer_name) AS name_upper, LOWER(city) AS city_lower FROM customers;
UPPER/LOWER do not change the stored value — only the query output
| customer_name | name_upper | city_lower |
|---|---|---|
| Amit Verma | AMIT VERMA | noida |
| Priya Sharma | PRIYA SHARMA | delhi |
| Rohan Mehta | ROHAN MEHTA | mumbai |
-- Case-insensitive search using LOWER SELECT product_name FROM products WHERE LOWER(product_name) LIKE '%cable%';
Matches 'HDMI Cable' even if the user typed 'cable', 'Cable', or 'CABLE'
| product_name |
|---|
| HDMI Cable |
On MySQL and SQL Server, string comparisons are case-insensitive by default (depending on collation). On PostgreSQL they are case-sensitive. Using LOWER() on both sides is the safest cross-database approach.
LENGTH — Count Characters
LENGTH(string) -- MySQL, PostgreSQL, SQLite
LEN(string) -- SQL Server
SELECT product_name, LENGTH(product_name) AS name_length FROM products ORDER BY name_length DESC;
| product_name | name_length |
|---|---|
| Ergonomic Chair | 15 |
| Wireless Mouse | 14 |
| Ballpoint Pens | 14 |
| Notebook A5 | 11 |
| USB-C Hub | 9 |
| Desk Lamp | 9 |
| HDMI Cable | 10 |
Use LENGTH in a WHERE clause to find data-quality issues:
WHERE LENGTH(phone) != 10 flags phone numbers that are not 10 digits.TRIM — Remove Whitespace
Data imported from CSV or Excel often has invisible leading/trailing spaces that break JOINs and comparisons. TRIM is the fix.
-- Simulate messy data with spaces
SELECT
' Amit Verma ' AS raw,
TRIM(' Amit Verma ') AS trimmed,
LTRIM(' Amit Verma ') AS left_trimmed,
RTRIM(' Amit Verma ') AS right_trimmed,
LENGTH(' Amit Verma ') AS raw_length,
LENGTH(TRIM(' Amit Verma ')) AS clean_length;Raw has 2 spaces on each side; TRIM removes all surrounding whitespace
| raw | trimmed | left_trimmed | right_trimmed | raw_length | clean_length |
|---|---|---|---|---|---|
| Amit Verma | Amit Verma | Amit Verma | Amit Verma | 14 | 10 |
CONCAT — Join Strings
CONCAT(str1, str2, ...) -- MySQL, PostgreSQL, SQL Server
str1 || str2 || str3 -- PostgreSQL, SQLite, Oracle (pipe operator)
str1 + str2 -- SQL Server alternative
-- Build a full address string SELECT customer_id, CONCAT(customer_name, ' — ', city) AS display_name FROM customers;
| customer_id | display_name |
|---|---|
| C01 | Amit Verma — Noida |
| C02 | Priya Sharma — Delhi |
| C03 | Rohan Mehta — Mumbai |
| C04 | Sneha Gupta — Noida |
| C05 | Arjun Singh — Bengaluru |
-- Build order reference codes
SELECT
order_id,
CONCAT('ORD-', order_id, '-', customer_id) AS order_ref
FROM orders
LIMIT 4;| order_id | order_ref |
|---|---|
| 1001 | ORD-1001-C01 |
| 1002 | ORD-1002-C02 |
| 1003 | ORD-1003-C01 |
| 1004 | ORD-1004-C03 |
CONCAT(value, NULL) returns NULL in standard SQL. Use
CONCAT_WS(separator, ...) in MySQL/PostgreSQL to safely skip NULLs: CONCAT_WS(', ', first, last) handles NULL gracefully.SUBSTRING — Extract Part of a String
SUBSTRING(string, start_pos, length)
-- start_pos is 1-indexed (first character = 1)
-- length is optional — omit to get everything from start_pos to end
SUBSTR(string, start, length) -- SQLite / Oracle alias
-- Extract the first word (first name) from customer_name -- and the category prefix (first 4 chars) SELECT customer_name, SUBSTRING(customer_name, 1, INSTR(customer_name, ' ') - 1) AS first_name, product_name, SUBSTRING(product_name, 1, 4) AS short_code FROM customers CROSS JOIN (SELECT product_name FROM products LIMIT 1) p LIMIT 3;
-- Simpler: LEFT / RIGHT shortcuts SELECT customer_id, LEFT(customer_id, 1) AS id_prefix, -- 'C' RIGHT(customer_id, 2) AS id_number -- '01', '02' ... FROM customers;
LEFT and RIGHT are shorthand for SUBSTRING from either end
| customer_id | id_prefix | id_number |
|---|---|---|
| C01 | C | 01 |
| C02 | C | 02 |
| C03 | C | 03 |
| C04 | C | 04 |
| C05 | C | 05 |
REPLACE — Swap One Substring for Another
REPLACE(string, old_substring, new_substring)
-- Rename a category in output without changing the table SELECT product_name, category, REPLACE(category, 'Electronics', 'Tech') AS category_clean FROM products WHERE category = 'Electronics';
| product_name | category | category_clean |
|---|---|---|
| Wireless Mouse | Electronics | Tech |
| USB-C Hub | Electronics | Tech |
| HDMI Cable | Electronics | Tech |
-- Remove unwanted characters (e.g. strip commas from a number field)
SELECT REPLACE('1,49,999', ',', '') AS clean_number;
-- Result: '1499999'REPLACE is case-sensitive in most databases. To do a case-insensitive replace, combine with UPPER/LOWER:
REPLACE(LOWER(col), 'old', 'new')Real-World Example — Data Cleaning in a Single Query
Combine string functions to standardise messy imported data:
-- Imagine raw customer data imported from a form:
-- names have random casing, emails have spaces, phone has dashes
SELECT
TRIM(UPPER(LEFT(customer_name, 1)))
|| LOWER(SUBSTRING(customer_name, 2)) AS name_clean,
LOWER(TRIM(email)) AS email_clean,
REPLACE(TRIM(phone), '-', '') AS phone_clean,
LENGTH(REPLACE(TRIM(phone), '-', '')) AS phone_digits
FROM raw_customers;All transformations happen in the SELECT — the raw table is unchanged
| name_clean | email_clean | phone_clean | phone_digits |
|---|---|---|---|
| Amit verma | amit@email.com | 9876543210 | 10 |
| Priya sharma | priya@email.com | 9812345678 | 10 |
Cross-Database Cheatsheet
| Task | MySQL | PostgreSQL | SQL Server |
|---|---|---|---|
| String length | LENGTH(s) | LENGTH(s) | LEN(s) |
| Substring | SUBSTRING(s,p,n) | SUBSTRING(s,p,n) | SUBSTRING(s,p,n) |
| Concatenate | CONCAT(a,b) | a || b | a + b |
| Find position | INSTR(s,sub) | POSITION(sub IN s) | CHARINDEX(sub,s) |
| Pad left | LPAD(s,n,pad) | LPAD(s,n,pad) | FORMAT / REPLICATE |
| Repeat string | REPEAT(s,n) | REPEAT(s,n) | REPLICATE(s,n) |
✏️ Practice Exercises
1. Write a query that shows each product name in UPPERCASE and its character count.
2. Build a "product code" by taking the first 3 letters of the category (UPPER) and joining them with the product_id using a hyphen.
3. Find all products whose name contains a space (use INSTR or LIKE).
Show Answers
-- 1. SELECT product_name, UPPER(product_name) AS name_upper, LENGTH(product_name) AS char_count FROM products; -- 2. SELECT product_id, product_name, CONCAT(UPPER(LEFT(category, 3)), '-', product_id) AS product_code FROM products; -- e.g. 'ELE-1', 'STA-3', 'FUR-5' -- 3. SELECT product_name FROM products WHERE product_name LIKE '% %'; -- or: WHERE INSTR(product_name, ' ') > 0