Skip to content
Back to 50 Concepts
Topic 22 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

String Functions Visual Simulator

Step 1 of 3
SQL>SELECT CONCAT_WS(', ', city, state, country) AS location FROM addresses;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for String Functions
SQL Input

Initiating String Functions

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Word processor toolbar: Cut, paste, uppercase, trim spaces, and find-replace.

4. Real-World Example

Sanitizing user-submitted phone numbers and emails before rendering or storage.

Input vs Output
Raw InputFunctionCleaned Output
Lucky@Gmail.com LOWER(TRIM(...))lucky@gmail.com
(555) 123-4567REPLACE(REPLACE(...))5551234567
Relational walkthrough: String functions ensure canonical format across user records.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Common text transformations
SELECT
  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

RuleBehavioral Explanation
1-Based IndexingIn SQL (unlike C or Python), SUBSTRING positions are 1-based: SUBSTRING("hello", 1, 2) returns "he".
NULL HandlingTRIM(NULL), UPPER(NULL), and SUBSTRING(NULL) all return NULL.
Multi-byte CharactersLENGTH() counts characters, while OCTET_LENGTH() counts physical bytes (UTF-8).
Character vs Byte lengthLENGTH() counts UTF-8 characters; OCTET_LENGTH() counts actual bytes consumed on disk.
Functional index on string transformsUsing 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';
Caution: Without an expression index, querying on functions forces a full table scan.

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

Scenario Question:

What does SUBSTRING('CSCosmos', 1, 2) return in standard SQL?

Select your answer: