SQL String Functions — CONCAT, SUBSTRING, TRIM, REPLACE
Reference for SQL string functions including CONCAT, SUBSTRING, UPPER, LOWER, TRIM, REPLACE, LENGTH, and dialect-specific functions for PostgreSQL, MySQL, and SQLite.
Functions
Detailed Explanation
Working with Text in SQL
String functions let you manipulate text values directly in your queries — concatenating, extracting substrings, changing case, and more.
Concatenation
-- Standard SQL / PostgreSQL
SELECT first_name || ' ' || last_name AS full_name FROM employees;
-- MySQL
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Case Conversion
SELECT UPPER(name) AS upper_name, LOWER(email) AS lower_email
FROM employees;
Substring Extraction
-- Extract first 3 characters
SELECT SUBSTRING(name, 1, 3) AS initials FROM employees;
-- PostgreSQL also supports LEFT/RIGHT
SELECT LEFT(name, 3), RIGHT(email, 10) FROM employees;
Trimming Whitespace
SELECT TRIM(name) AS trimmed FROM employees;
SELECT LTRIM(name), RTRIM(name) FROM employees;
-- Trim specific characters (PostgreSQL)
SELECT TRIM(BOTH '-' FROM slug) FROM articles;
Replace and Length
SELECT REPLACE(email, '@old.com', '@new.com') AS migrated_email
FROM employees;
SELECT name, LENGTH(name) AS name_length FROM employees;
Dialect-Specific Highlights
PostgreSQL:
INITCAP(str)— capitalize first letter of each wordREGEXP_REPLACE(str, pattern, replacement, flags)STRING_AGG(col, delimiter)— concatenate group values
MySQL:
CONCAT_WS(separator, str1, str2, ...)— concat with separatorLOCATE(substr, str)— find positionLPAD(str, len, pad)/RPAD— pad stringsGROUP_CONCAT(col SEPARATOR ',')
SQLite:
SUBSTR(str, start, length)instead of SUBSTRINGGROUP_CONCAT(col, separator)- Limited built-in string functions; no regex by default
Use Case
You are cleaning or transforming text data in queries — such as normalizing email addresses, building display names from first/last name columns, or extracting parts of structured strings.