SQL-Engineering-Handbook

04 — String Cleaning & Validation

🏠 Module Home · 🗂️ Handbook Home · ← 03 String Transformation · Next → 05 Business String Analytics

String Cleaning and Validation

Introduction

Topics 01–03 gave you the primitives: measure, slice, search, transform. This topic is about combining them into repeatable cleaning and validation routines — the kind that run in an ETL pipeline before dirty data ever reaches a report. Using a healthcare intake schema (patient records, contact details), this topic covers whitespace normalization, structural validation of emails and phone numbers, and standardization rules for names and addresses.

Concept Overview

This topic introduces no new functions — it is a synthesis topic, applying TRIM, UPPER/LOWER, REPLACE, LOCATE, LIKE, and REGEXP together as validation and cleaning patterns rather than isolated function calls. The shift here is from “what does this function do” to “what sequence of functions constitutes a defensible cleaning rule.”

Business Motivation

Data quality failures compound: a phone number stored with inconsistent formatting causes a failed SMS notification; an email stored with leading whitespace fails a downstream API’s strict validation; a patient name stored inconsistently across two systems causes a failed record match during a care transition. In regulated domains like healthcare, these aren’t just inconvenient — they’re compliance and patient-safety issues. Cleaning and validation exist to catch these problems at the query layer, before they propagate.

Why These Patterns Exist

No single string function validates “is this a real email” or “is this phone number usable” — validation is inherently a composition of several checks (structural pattern, length bounds, absence of known-bad values). This topic exists to show that composition explicitly, rather than leaving it as an implicit skill assumed by later topics.

Real Company Use Cases

Functions Covered

This topic combines, rather than introduces: TRIM(), UPPER()/LOWER(), REPLACE(), LOCATE(), LIKE, REGEXP, CHAR_LENGTH().

Syntax

No new syntax — see Topics 01–03 for individual function signatures. This topic’s syntax is compositional, e.g.:

TRIM(REPLACE(LOWER(email), ' ', ''))

Parameters

N/A — parameters are as documented in Topics 01–03 for each underlying function.

Return Values

N/A at the individual-function level. Validation queries in this topic typically return a boolean (via CASE/WHERE) summarizing whether a value passes a composed rule.

ASCII Visual Explanation

Cleaning pipeline for a patient contact phone number:

  raw_phone
     │
     ▼
  TRIM()                 — remove leading/trailing whitespace
     │
     ▼
  REPLACE(., '.', '-')    — normalize separator characters
  REPLACE(., ' ', '-')
     │
     ▼
  LIKE pattern check      — validate final structure
     │
     ▼
  clean_phone  (or flagged as invalid)

Step-by-Step Examples

Goal: Validate that a patient email has a minimally plausible structure before it’s marked eligible for automated appointment reminders.

SELECT
    patient_id,
    patient_email,
    CASE
        WHEN patient_email IS NULL THEN 'Missing'
        WHEN TRIM(patient_email) = '' THEN 'Empty'
        WHEN LOCATE('@', TRIM(patient_email)) = 0 THEN 'Missing @'
        WHEN LOCATE('.', SUBSTRING_INDEX(TRIM(patient_email), '@', -1)) = 0 THEN 'Missing domain dot'
        ELSE 'Passes basic structure check'
    END AS email_validation_status
FROM patients;

Reasoning: Each WHEN clause checks one specific, named failure mode in order of severity (missing entirely, empty after trimming, missing @, missing a . in the domain portion), producing an actionable status rather than a bare TRUE/FALSE that would require re-deriving why a record failed.

Production Considerations

Performance Notes

Edge Cases

Common Mistakes

Best Practices

Interview Questions

  1. Why is WHERE email LIKE '%@%.%' insufficient as a complete email validation strategy, and what would you add?
  2. How do you handle NULL correctly inside a CASE-based validation expression, and what happens if you don’t?
  3. Design a CASE expression that reports why a phone number failed validation, not just that it failed.
  4. When should data cleaning happen in SQL versus in an application/ETL layer?

Practice Challenges

  1. Write a validation query for patient_phone that flags records as Missing, Too Short, or Valid, based on CHAR_LENGTH() after removing all non-digit separator characters.
  2. Build a cleaning query that trims whitespace, collapses double spaces to single spaces, and title-cases a patient_name field (title-casing may require combining functions creatively, since most engines lack a native INITCAP()-equivalent — note where your engine does provide one).
  3. Write a query identifying patients whose email and phone are both missing or invalid, as a worklist for manual outreach follow-up.

Summary

Cleaning and validation are compositions of the functions from Topics 01–03, applied with a specific goal: catching bad data before it propagates, and doing so in a way that reports why a record failed, not just that it did. This topic is the bridge between knowing individual string functions and using them as a production data-quality practice.

Further Reading


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