String Functions
Transform, extract, and manipulate text data with SQL string functions.
- UPPER / LOWER â change case
- SUBSTRING / LENGTH â extract and measure String functions turn raw text into useful information.
What Are String Functions?
-- Basic string function usage
SELECT UPPER(first_name) AS upper_name,
LOWER(last_name) AS lower_name,
LENGTH(first_name) AS name_length
FROM employees;
UPPER and LOWER
-- Standardize email formats
SELECT LOWER(email) AS standardized_email
FROM customers;
-- Case-insensitive search
SELECT * FROM employees
WHERE UPPER(department) = UPPER('engineering');
-- Display formatting
SELECT CONCAT(UPPER(LEFT(first_name, 1)), LOWER(SUBSTRING(first_name, 2))) AS formatted_name
FROM employees;
LENGTH
-- Find long employee names
SELECT first_name, last_name,
LENGTH(first_name) + LENGTH(last_name) AS total_length
FROM employees
WHERE LENGTH(first_name) + LENGTH(last_name) > 15;
-- Validate data quality
SELECT email,
LENGTH(email) AS email_length
FROM customers
WHERE LENGTH(email) < 5;
SUBSTRING
-- Extract area codes from phone numbers
SELECT phone_number,
SUBSTRING(phone_number, 1, 3) AS area_code
FROM employees;
-- Get first initial
SELECT CONCAT(SUBSTRING(first_name, 1, 1), '.', SUBSTRING(last_name, 1, 1)) AS initials
FROM employees;
-- Extract domain from email
SELECT email,
SUBSTRING(email, LOCATE('@', email) + 1) AS domain
FROM customers;
CONCAT
-- Full name from parts
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
-- Build formatted output
SELECT CONCAT(department, ' - ', job_title, ' (', employee_id, ')') AS employee_info
FROM employees;
-- CONCAT_WS for delimited strings
SELECT CONCAT_WS(', ', first_name, last_name, city) AS contact_info
FROM employees;
TRIM, LTRIM, RTRIM
-- Clean imported data
SELECT TRIM(first_name) AS cleaned_name,
LENGTH(TRIM(first_name)) AS cleaned_length,
LENGTH(first_name) AS original_length
FROM employees
WHERE first_name != TRIM(first_name);
-- Remove specific characters
SELECT TRIM(BOTH '0' FROM product_code) AS trimmed_code
FROM products;
REPLACE
-- Clean phone number formatting
SELECT phone_number,
REPLACE(REPLACE(phone_number, '-', ''), ' ', '') AS clean_phone
FROM employees;
-- Redact sensitive data
SELECT CONCAT(LEFT(email, 2), '***@', SUBSTRING(email, LOCATE('@', email) + 1)) AS masked_email
FROM customers;
LEFT and RIGHT
-- Extract first 3 characters
SELECT LEFT(department, 3) AS dept_code
FROM employees;
-- Extract file extension
SELECT file_name,
RIGHT(file_name, LENGTH(file_name) - LOCATE('.', REVERSE(file_name))) AS extension
FROM uploaded_files;
CHAR_LENGTH vs OCTET_LENGTH
-- Character length vs byte length
SELECT first_name,
CHAR_LENGTH(first_name) AS char_count,
OCTET_LENGTH(first_name) AS byte_count
FROM employees;
String Functions with Aggregates
-- Most common department names
SELECT department, COUNT(*) AS cnt
FROM employees
GROUP BY UPPER(TRIM(department))
ORDER BY cnt DESC;
-- String length statistics
SELECT department,
AVG(LENGTH(first_name)) AS avg_name_length,
MIN(LENGTH(first_name)) AS shortest_name,
MAX(LENGTH(first_name)) AS longest_name
FROM employees
GROUP BY department;
Pattern Matching with LIKE
-- Names starting with 'J'
SELECT * FROM employees
WHERE first_name LIKE 'J%';
-- Emails containing a specific domain
SELECT * FROM customers
WHERE email LIKE '%@gmail.com';
-- Phone numbers with specific pattern
SELECT * FROM employees
WHERE phone_number LIKE '___-___-____';
Real-World String Transformations
-- Generate username from name
SELECT CONCAT(LOWER(SUBSTRING(first_name, 1, 1)), LOWER(last_name)) AS username
FROM employees;
-- Parse full name into components
SELECT SUBSTRING_INDEX(full_name, ' ', 1) AS first_name,
SUBSTRING_INDEX(full_name, ' ', -1) AS last_name
FROM customers;
-- Format currency strings
SELECT CONCAT('$', FORMAT(salary, 2)) AS formatted_salary
FROM employees;
Common String Function Reference
| Function | Syntax | Purpose |
|---|---|---|
| UPPER | UPPER(string) | Convert to uppercase |
| LOWER | LOWER(string) | Convert to lowercase |
| LENGTH | LENGTH(string) | Get character count |
| SUBSTRING | SUBSTRING(string, start, len) | Extract portion |
| CONCAT | CONCAT(str1, str2, ...) | Join strings |
| TRIM | TRIM(string) | Remove whitespace |
| REPLACE | REPLACE(string, search, repl) | Substitute text |
| LEFT | LEFT(string, n) | First N characters |
| RIGHT | RIGHT(string, n) | Last N characters |
| LOCATE | LOCATE(sub, string) | Find position |
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions