SQL String Functions โ Cleaning & Transforming Text Data
In real-world databases, a huge amount of information is stored as text:
โข Customer names
โข Email addresses
โข Phone numbers
โข Product names
โข Cities
โข Categories
โข Addresses
โข Job titles
But text data is rarely perfectly clean.
You may encounter:
โข
' Alice 'โข
'alice@example.com'โข
'ALICE@EXAMPLE.COM'โข
'Premium Customer'โข
' Mumbai'SQL string functions allow you to clean, search, extract, combine, and transform text directly inside your queries.
๐ง 1. What Are String Functions?
String functions are SQL functions that operate on text values.
Common functions include:
โข
LENGTH()โข
UPPER()โข
LOWER()โข
TRIM()โข
LTRIM()โข
RTRIM()โข
SUBSTRING()โข
LEFT()โข
RIGHT()โข
CONCAT()โข
REPLACE()โข
POSITION()โข
CHAR_LENGTH()Exact function names and syntax can vary slightly between databases such as PostgreSQL, MySQL, SQL Server, and Oracle.
๐ 2. UPPER()
Converts text to uppercase.
SELECT
customer_name,
UPPER(customer_name) AS uppercase_name
FROM customers;
Example:
Alice becomes ALICE
Useful for:
โข Standardizing text
โข Case-insensitive comparisons
โข Creating reports
โข Data cleaning
๐ก 3. LOWER()
Converts text to lowercase.
SELECT
LOWER(email) AS email
FROM customers;
Example:
ALICE@EXAMPLE.COM becomes alice@example.comA common data-cleaning pattern is:
SELECT
LOWER(TRIM(email)) AS cleaned_email
FROM customers;
This handles both unnecessary spaces and inconsistent capitalization.
๐งน 4. TRIM()
Removes leading and trailing spaces.
SELECT
TRIM(customer_name) AS cleaned_name
FROM customers;
For example
' Alice ' becomes 'Alice'This is extremely useful when importing data from Excel, CSV files, APIs, and external systems.
โฉ๏ธ 5. LTRIM() and RTRIM()
โข
LTRIM() removes spaces from the beginning:SELECT LTRIM(customer_name) FROM customers;
โข
RTRIM() removes spaces from the end:SELECT RTRIM(customer_name) FROM customers;
โข While
TRIM() generally handles both sides:SELECT TRIM(customer_name) FROM customers;
๐ 6. LENGTH()
Returns the number of characters in a string.
SELECT
customer_name,
LENGTH(customer_name) AS name_length
FROM customers;
Example:
โข Alice โ 5
โข Robert โ 6
Function behavior can vary across SQL dialects, particularly with multibyte characters.
๐ 7. Finding Long or Short Values
String length can be useful for data-quality checks.
Example:
SELECT * FROM customers WHERE LENGTH(phone) < 10;
This can help identify potentially invalid phone numbers.
SELECT * FROM products WHERE LENGTH(product_name) > 100;
This can identify unusually long product descriptions.
โ๏ธ 8. SUBSTRING()
SUBSTRING() extracts part of a string.A common form is:
SUBSTRING(column_name, start_position, length)SELECT SUBSTRING(customer_name, 1, 3) AS first_three_characters FROM customers;
For Alexander the result would be
Ale.Syntax differs by database, so always check the dialect you're using.
๐ 9. LEFT()
Returns characters from the beginning of a string.