# Topic 22: String Functions
Text manipulation: CONCAT, SUBSTRING, LENGTH, TRIM, REPLACE, UPPER/LOWER, and regular expression matching.
1. Definition
SQL string functions manipulate, clean, extract, and format text data stored in CHAR, VARCHAR, or TEXT columns.
2. Explain Like I'm 5
String functions are text tools like scissors (SUBSTRING), glue (CONCAT), an eraser (TRIM), or a dictionary search-and-replace.
3. Animation & Visual Simulation
Interactive Engine TraceString Functions Visual Simulator
SELECT CONCAT_WS(', ', city, state, country) AS location
FROM addresses;Active InputStep 1: Input & Parsing Stage
Initiating String Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Sanitizing user-submitted phone numbers and emails before rendering or storage.
| Raw Input | Function | Cleaned Output |
|---|---|---|
| Lucky@Gmail.com | LOWER(TRIM(...)) | lucky@gmail.com |
| (555) 123-4567 | REPLACE(REPLACE(...)) | 5551234567 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT LOWER(TRIM(email)) AS normalized_email, CONCAT(first_name, ' ', last_name) AS full_name, SUBSTRING(phone FROM 1 FOR 3) AS area_code, LENGTH(password_hash) AS hash_length, REPLACE(description, 'bad', 'good') AS clean_desc FROM users;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| 1-Based Indexing | In SQL (unlike C or Python), SUBSTRING positions are 1-based: SUBSTRING("hello", 1, 2) returns "he". |
| NULL Handling | TRIM(NULL), UPPER(NULL), and SUBSTRING(NULL) all return NULL. |
| Multi-byte Characters | LENGTH() counts characters, while OCTET_LENGTH() counts physical bytes (UTF-8). |
| Character vs Byte length | LENGTH() counts UTF-8 characters; OCTET_LENGTH() counts actual bytes consumed on disk. |
| Functional index on string transforms | Using UPPER(email) or LOWER(name) requires an expression index to prevent full table scans. |
7. Deep Dive: Expression Indexes for Case-Insensitive Queries
Using LOWER(email) in a WHERE clause prevents the engine from using a normal index on email. Creating an expression index solves this completely.
-- Create expression index on normalized text: CREATE INDEX idx_users_lower_email ON users(LOWER(email)); -- Now this uses an Index Scan: SELECT * FROM users WHERE LOWER(email) = 'lucky@example.com';
8. Advantages & Disadvantages
Advantages
- •Transforms data on the fly directly inside the database.
- •Enables data standardization and cleaning during ingestion.
Disadvantages & Trade-offs
- •Overusing string manipulation functions in WHERE without expression indexes disables B-Trees.
9. Common Interview Questions
Q1.What is the difference between LENGTH() and OCTET_LENGTH() in SQL?
LENGTH(str) returns the count of unicode characters (characters seen by human eyes). OCTET_LENGTH(str) returns the exact number of bytes used to store the string in memory or disk. For multi-byte characters (like emojis or non-Latin alphabets), LENGTH('🚀') is 1, while OCTET_LENGTH('🚀') is 4 bytes. In network protocols and buffer allocations, always use OCTET_LENGTH.
Q2.What is the difference between CONCAT() and the standard || operator regarding NULL handling?
In standard ANSI SQL, the concatenation operator (||) follows Three-Valued Logic: if ANY operand is NULL, the entire result becomes NULL ('Hello ' || NULL yields NULL). The CONCAT() function in PostgreSQL and MySQL treats NULL as an empty string, safely joining remaining strings without returning NULL.
Q3.How do you perform regex pattern matching and replacement in PostgreSQL?
PostgreSQL provides POSIX regular expression operators: ~ (case-sensitive match), ~* (case-insensitive match), !~ (does not match), and REGEXP_REPLACE(source, pattern, replacement, flags). For example, REGEXP_REPLACE(phone, '[^0-9]', '', 'g') strips all non-numeric characters from a phone number.
Q4.Why does SUBSTRING indexing require an Expression Index?
If a query filters with WHERE SUBSTRING(account_number, 1, 4) = 'ACCT', a standard B-Tree index on account_number cannot be used because the B-Tree keys store the entire string. To achieve fast index seeks, you must create a functional expression index: CREATE INDEX idx_acc_prefix ON accounts ((SUBSTRING(account_number, 1, 4)));
Q5.What is the difference between TRIM, LTRIM, and RTRIM?
TRIM removes specified characters (defaulting to whitespace) from both the leading and trailing ends of a string. LTRIM removes whitespace only from the left (leading) end. RTRIM removes whitespace only from the right (trailing) end. Modern ANSI SQL also supports TRIM(LEADING '0' FROM code).
10. Interview-Ready Answer
“SQL provides standard text functions like CONCAT, SUBSTRING, TRIM, and REPLACE. String indexes are 1-based, and when string transformations are used in WHERE predicates, expression indexes are required to preserve logarithmic B-Tree lookups.”
11. Quick Test
What does SUBSTRING('CSCosmos', 1, 2) return in standard SQL?