SQL String
Functions
Learn how to manipulate text data in SQL using SUBSTRING, CONCAT, and TRIM: the essential toolkit for working with strings in any database.
What Are Strings in SQL?
A string is any sequence of characters stored as text in a database column. Names, emails, addresses, product descriptions: they are all strings. In SQL, string values are enclosed in single quotes.
Why String Functions Matter
The Big Three: SUBSTRING, CONCAT, TRIM
SUBSTRING: Extract a Piece
Visualizing SUBSTRING
CONCAT: Join Strings Together
CONCAT takes two or more string arguments and returns them glued together in order. It does not add any separator automatically: if you want a space between words, you must include it yourself.
Visualizing CONCAT
TRIM: Clean Up Whitespace
TRIM removes spaces (or specified characters) from both ends of a string. LTRIM strips the left side only; RTRIM strips the right side only. Inner spaces are never removed.
Visualizing TRIM
SUBSTRING vs CONCAT vs TRIM
| SUBSTRING | CONCAT | TRIM | |
|---|---|---|---|
| Purpose | Extract part | Join parts | Remove edges |
| Inputs | 1 string + position | 2+ strings | 1 string |
| Output length | Shorter or equal | Longer or equal | Shorter or equal |
| Changes content? | Selects a portion | Combines all | Removes spaces |
How to Apply String Functions
CONCAT(TRIM(first), ' ', TRIM(last)).Example 1: Extract Area Codes
Given a phone column with values like '(415) 555-1234', extract just the 3-digit area code.
Example 2: Build a Full Name
Combine first_name and last_name columns into a formatted display name, cleaning any extra spaces first.
Example 3: Create a Username
Generate a username from first initial + last name: 'Ada' + 'Lovelace' → 'ALovelace'.
Common Mistakes
CONCAT('A','B') gives 'AB', not 'A B'. Always include an explicit space string.TRIM('a b') still returns 'a b'.Quick Reference Cheat Sheet
| Function | Syntax | Example | Result |
|---|---|---|---|
| SUBSTRING | SUBSTRING(str, start, len) | SUBSTRING('Hello', 2, 3) | 'ell' |
| CONCAT | CONCAT(str1, str2, ...) | CONCAT('Hi', ' ', 'there') | 'Hi there' |
| TRIM | TRIM(str) | TRIM(' Hi ') | 'Hi' |
| LTRIM | LTRIM(str) | LTRIM(' Hi ') | 'Hi ' |
| RTRIM | RTRIM(str) | RTRIM(' Hi ') | ' Hi' |
Question 1 of 5
What does SUBSTRING('COMPUTER', 4, 3) return?
Question 2 of 5
Which SQL expression correctly joins two separate strings 'Hello' and 'World' with a space between them?
Question 3 of 5
What does TRIM(' data ') return?
Question 4 of 5
A table has columns first_name and last_name. Which query produces usernames like 'ALovelace' (first initial + last name)?
Question 5 of 5
In standard SQL, what is the starting index of the first character in a string?