SQL-Engineering-Handbook

01 — Basic String Functions

🏠 Module Home · 🗂️ Handbook Home · Next → 02 String Search & Extraction

Basic String Functions

Introduction

Every string-heavy query in this handbook builds on a small set of foundational operations: measuring text, changing its case, slicing it, joining it together, and finding a character’s position within it. This topic covers that foundation using an HR schema — employee names, department assignments, and derived usernames — the same category of problem you’ll meet in almost any production system with a users or employees table.

Concept Overview

Basic string functions fall into four families:

  1. MeasurementLENGTH(), CHAR_LENGTH()
  2. Case conversionUPPER(), LOWER()
  3. SlicingLEFT(), RIGHT(), SUBSTRING() / MID()
  4. Assembly & cleanupCONCAT(), CONCAT_WS(), TRIM(), LTRIM(), RTRIM()

Positional search (LOCATE()) is included here as the simplest form of string search, with the fuller search/extraction toolkit (POSITION, INSTR, LIKE, REGEXP) reserved for Topic 02.

Business Motivation

Raw employee, customer, or product name fields are rarely used as-is downstream. Reports need consistent casing. Systems need derived identifiers (usernames, initials, short codes) built from existing fields. Data entered by hand needs its whitespace and formatting normalized before it can be trusted in a JOIN or GROUP BY. Basic string functions are the tools that make all of this possible without leaving the database layer.

Why These Functions Exist

Relational databases store text as opaque byte/character sequences — there is no built-in concept of “first name” versus “last name” within a single VARCHAR column, no automatic case normalization, and no automatic whitespace handling. Basic string functions exist to give SQL the same text-manipulation primitives available in any general-purpose programming language, so that formatting and parsing logic doesn’t have to be pushed into the application layer for simple cases.

Real Company Use Cases

Functions Covered

Function Purpose
LENGTH() Byte length of a string
CHAR_LENGTH() Character count of a string (safe for multi-byte text)
UPPER() Converts text to uppercase
LOWER() Converts text to lowercase
LEFT() Returns the leftmost N characters
RIGHT() Returns the rightmost N characters
SUBSTRING() / MID() Returns a substring starting at a given position
CONCAT() Joins two or more strings
CONCAT_WS() Joins strings with a separator, skipping NULLs
TRIM() / LTRIM() / RTRIM() Removes leading/trailing/both whitespace
LOCATE() Returns the position of a substring within a string

Syntax

LENGTH(str)
CHAR_LENGTH(str)
UPPER(str)
LOWER(str)
LEFT(str, n)
RIGHT(str, n)
SUBSTRING(str, start [, length])
CONCAT(str1, str2, ...)
CONCAT_WS(separator, str1, str2, ...)
TRIM([BOTH | LEADING | TRAILING] [chars FROM] str)
LOCATE(substr, str [, start_position])

Parameters

Return Values

ASCII Visual Explanation

emp_name = "SARAH CONNOR"

LEFT(emp_name, 3)              →  "SAR"
                                     ^^^
                                     positions 1-3

RIGHT(emp_name, 2)             →  "OR"
                                          ^^
                                    last 2 characters

LOCATE('a', emp_name)          →  position of first lowercase/uppercase 'a'... 
                                    NOTE: case sensitivity is engine-dependent (see Edge Cases)

Step-by-Step Examples

Goal: Build a login username from an employee’s name and ID.

SELECT
    emp_name,
    emp_id,
    CONCAT(UPPER(LEFT(emp_name, 3)), emp_id) AS username
FROM employees;

Reasoning: LEFT(emp_name, 3) isolates the first three characters, UPPER() guarantees consistent casing regardless of how the name was entered, and CONCAT() appends the numeric ID to guarantee uniqueness even when two employees share the same first three letters.

Production Considerations

Performance Notes

Edge Cases

Common Mistakes

Best Practices

Interview Questions

  1. What’s the difference between LENGTH() and CHAR_LENGTH(), and when would they return different values?
  2. Why might CONCAT(first_name, ' ', last_name) return NULL for some rows, and how would you fix it?
  3. Given a column of freeform names, write a query to generate a firstname.lastname style username in lowercase, assuming names are guaranteed to have exactly one space.
  4. Why does filtering with WHERE UPPER(col) = 'X' often hurt query performance on large tables, and what are two ways to avoid the problem?

Practice Challenges

  1. Write a query that returns each employee’s initials (first letter of each word in emp_name), assuming names may have two or three words.
  2. Using CONCAT_WS(), build a single “mailing label” style string from emp_name, dept_name, and city, gracefully handling any of the three being NULL.
  3. Identify which employee names in the table exceed 20 characters using CHAR_LENGTH(), and explain why LENGTH() would be the wrong choice if the names contained accented characters.

Summary

Basic string functions — measurement, case conversion, slicing, assembly, and trimming — are the primitives every later topic in this module builds on. The recurring theme across all of them is defensive handling of NULL, whitespace, and encoding assumptions; the functions themselves are simple, but production-safe usage requires anticipating how real data breaks those assumptions.

Further Reading


⬆ Back to top · 🏠 Module Home · 🗂️ Handbook Home