🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Management / Database Administration › Data Governance & Quality › Lesson 4
TEC-DATA86-07 · Lesson 4 · 11 clock hours · lab

Data Cleansing and Standardization Techniques

Objective. Students will write SQL and Python routines to correct, standardize, and reject data-quality violations identified in the profiling lab, applying transformations in a staging-to-target ETL pattern.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Data Cleansing and Standardization Techniques

Why Cleansing Matters

Raw operational data is rarely ready for analysis or reporting. Fields arrive with inconsistent formatting, missing values, duplicate rows, and values that violate business rules. Data cleansing is the process of detecting and correcting — or rejecting — those problems so that the target table meets defined quality standards. In a staging-to-target ETL (Extract, Transform, Load) pattern, you never modify the source system. Instead, you land raw data in a staging area, apply corrections there, and promote only acceptable records to the target table. Records that cannot be fixed are quarantined with a documented reason.

The Staging-to-Target Pattern

A staging table is a temporary or permanent holding area that mirrors the structure of the source. Working in staging protects the source and gives you a repeatable, auditable trail:

1. Extract — copy raw data into the staging table as-is.

2. Transform — apply cleansing rules in staging: fix what can be fixed, flag what cannot.

3. Load — INSERT only clean records into the target table; route rejected records to a quarantine (rejected_records) table with a `rejection_reason` column.

This approach supports rollback, re-processing, and audit requirements that governance frameworks such as DAMA-DMBOK expect.

Common SQL Cleansing Operations

NULL substitution — Replace a NULL with a known default only when the business rule permits it. Use `COALESCE` or an `UPDATE … WHERE column IS NULL` statement. Document why the substitution is acceptable.

Whitespace trimming — Leading and trailing spaces cause silent join failures and inflate distinct-value counts. Use `TRIM(column)` or `BTRIM(column)` in PostgreSQL. Apply as an UPDATE on the staging table before any other transformation.

Date standardization — Store dates as the PostgreSQL `DATE` or `TIMESTAMP` type, never as free-text. Use `TO_DATE(string, 'format')` to parse common patterns such as `MM/DD/YYYY` or `DD-MON-YYYY`, and insert the result into a properly typed column.

Phone number standardization — Strip all non-digit characters with `REGEXP_REPLACE(phone, '[^0-9]', '', 'g')`, then validate that the result is exactly 10 digits for a US number. Records with fewer or more digits are unfixable and go to quarantine.

Flagging uncorrectable records — When a value violates a rule and no safe correction exists, insert the row into `rejected_records` with a plain-language `rejection_reason`, then DELETE it from staging so it never reaches the target.

Deduplication — Use a `ROW_NUMBER()` window function partitioned by the natural key to identify duplicates, then delete all but the row with the lowest or most recent primary key.

Python-Based Standardization with pandas

SQL handles structured transformations well, but semi-structured fields such as free-text addresses and email addresses are better handled with regular expressions in Python.

pandas loads the staging table via `psycopg2` (or `SQLAlchemy`) into a `DataFrame`. You then apply `Series.str.replace()` or `Series.str.extract()` with compiled regex patterns. For email fields, a pattern such as `^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$` validates format; rows that do not match are routed to a rejected DataFrame.

After transformation, use `DataFrame.to_sql()` or a `psycopg2` `executemany()` call to reload clean records into the PostgreSQL target table. Always use parameterized queries — never string-format user-supplied values into SQL, because that creates SQL injection risk.

Handling encoding issues — When reading CSVs, specify `encoding='utf-8'` explicitly. Unexpected characters can corrupt string comparisons and should be stripped or replaced before regex rules run.

Validating Results with Great Expectations

After loading the target table, re-run the same Great Expectations expectation suite you built in the profiling lab. Great Expectations returns a validation result that shows how many expectations passed and failed. Calculate the improvement delta:

Document every expectation that still fails and explain whether the failure is a data problem or a rule that needs revision.

Safety and Data Integrity Practices

Database work carries specific risks that are analogous to physical safety rules:

Putting It Together

A complete cleansing pipeline for this lab runs in this order: trim whitespace → standardize dates and phones in SQL → run Python regex rules on address and email fields → reload → quarantine rejects with reasons → validate with Great Expectations → document. The target table must pass at least 90 percent of expectation assertions to meet the lesson threshold. Any rejected record must appear in the `rejected_records` table with a populated `rejection_reason` column.

Key terms10

Staging tableA holding table that receives raw source data before any cleansing or transformation; changes are made here, not in the source system.
ETL (Extract, Transform, Load)A data-integration pattern in which data is extracted from a source, transformed to meet quality and format rules, and loaded into a target store.
NULL substitutionReplacing a NULL value with a business-approved default when the absence of a value would cause downstream errors and a safe default exists.
REGEXP_REPLACEA PostgreSQL function that replaces substrings matching a regular-expression pattern with a specified replacement string, used here to strip non-digit characters from phone fields.
Rejected-records table (quarantine)A separate table that holds rows removed from staging because they could not be corrected, along with a rejection_reason column explaining the specific violation.
Parameterized queryA SQL statement in which user-supplied values are passed as separate parameters rather than concatenated into the query string, preventing SQL injection attacks.
Great ExpectationsAn open-source Python framework that defines, runs, and documents data-quality assertions (expectations) against a dataset and returns a validation result.
Improvement deltaThe numeric difference between the post-cleansing expectation-pass rate and the pre-cleansing expectation-pass rate, used to measure how much a cleansing pipeline improved data quality.
Window function (ROW_NUMBER)A SQL function that assigns a sequential number to rows within a partition, commonly used to identify and remove duplicate records while retaining one canonical row.
Data classification policyAn organizational policy that assigns sensitivity levels (e.g., public, internal, confidential, restricted) to data assets and dictates handling, storage, and access controls for each level.
In class: Using the dirty dataset from Lesson 3, write a series of SQL UPDATE, DELETE, and INSERT … SELECT statements that fix NULL substitutions, trim whitespace, standardize phone and date formats, and flag records that cannot be corrected. · Build a Python script using pandas that applies regular-expression-based standardization rules to address and email fields, then reloads the cleaned records into a PostgreSQL target table. · Re-run the Great Expectations suite on the cleaned target table, document the improvement in dimension scores, and write a one-page summary of any records rejected and why.
Materials: PostgreSQL 15, Python 3.x with pandas and psycopg2, DBeaver CE, Great Expectations, earlier profiling report, instructor-provided correction rules reference
Check: Target table passes at least 90% of expectation suite assertions; rejected-records table is populated with a rejection_reason column; improvement delta is calculated and documented — both code and report must meet threshold to pass.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data Governance & Data Quality (DAMA CDMP)
1. In a staging-to-target ETL pattern, where should bulk UPDATE statements that fix NULL values be executed?
Database Administration — SQL (Oracle DBA CA / PostgreSQL CE)
2. A phone column contains values like '(555) 123-4567', '555.123.4567', and '5551234567'. Which PostgreSQL expression standardizes all three to the 10-digit string '5551234567'?
Data Governance & Data Quality (DAMA CDMP)
3. After running a cleansing pipeline, 47 out of 50 Great Expectations assertions pass on the target table. What is the pass rate, and does it meet the 90% threshold required by this lab?
Database Security (Microsoft DP-300 / Oracle DBA CA)
4. You are writing a Python script to validate email addresses before loading them into PostgreSQL. Which practice is most important for security when inserting the cleaned rows?
Database Administration — SQL (Oracle DBA CA / PostgreSQL CE)
5. Which PostgreSQL window-function construct correctly identifies duplicate rows in a staging table so that only one row per customer_id is kept?
Database Administration — SQL (PostgreSQL CE / Oracle DBA CA)
6. A record has a date field containing the string 'Jan 5 2023'. Which PostgreSQL expression correctly converts it to a DATE value?
Database Administration — Operations (Oracle DBA CA / Microsoft DP-300)
7. Before executing a DELETE statement that will remove thousands of rows from the staging table, what is the most important safety step?
Data Governance (DAMA CDMP)
8. According to DAMA-DMBOK principles, why must rejected records be stored in a quarantine table with a rejection_reason column rather than simply deleted?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.