🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

String Functions

SQL AggregationString FunctionsđŸŸĸ Free Lesson
SQL Aggregation

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?

String Functions ReferenceTransformUPPER('abc') → ABCLOWER('ABC') → abcTRIM(' a ') → aREPLACE(a,b,c) → cCONCAT(a,b) → abModify text contentExtractSUBSTRING(s, 1, 3)LEFT(s, 2) → first 2RIGHT(s, 2) → last 2LOCATE('@', email)CHAR_LENGTH(s)Pull parts from textAnalyzeLIKE 'J%' → patternLENGTH(s) → countPOSITION(x IN s)OCTET_LENGTH(s)SOUNDEX(s) → phoneticSearch & measure text
-- 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

FunctionSyntaxPurpose
UPPERUPPER(string)Convert to uppercase
LOWERLOWER(string)Convert to lowercase
LENGTHLENGTH(string)Get character count
SUBSTRINGSUBSTRING(string, start, len)Extract portion
CONCATCONCAT(str1, str2, ...)Join strings
TRIMTRIM(string)Remove whitespace
REPLACEREPLACE(string, search, repl)Substitute text
LEFTLEFT(string, n)First N characters
RIGHTRIGHT(string, n)Last N characters
LOCATELOCATE(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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement