🚧 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 › ETL Pipelines: Extract, Transform, and Load for Database Administration › Lesson 3
TEC-DATA86-06 · Lesson 3 · 12.5 clock hours · lab

Transformation Logic: Cleaning, Casting, and Business Rules

Objective. Students will apply a set of specified transformation rules — null substitution, data-type casting, deduplication, and a business-rule filter — to a staging dataset and produce a clean output file that passes automated validation.

⚠ 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.

Transformation Logic: Cleaning, Casting, and Business Rules

The transformation stage is the most complex part of any ETL pipeline. Extracting raw data from a source is relatively mechanical; loading clean data into a target is straightforward. What happens in between — cleaning, casting, deduplicating, and applying business rules — determines whether the data warehouse or operational database becomes an asset or a liability. This lesson walks through each category of transformation logic you will apply in today's lab.

Why Transformation Matters

Raw operational data almost always contains defects: missing values, inconsistent formats, duplicate records, and values that violate business constraints. If these defects reach the target database, every downstream query, report, and decision that touches that data is compromised. The DAMA DMBOK2 defines data quality in terms of dimensions such as completeness, consistency, accuracy, and timeliness. Your transformation script is the enforcement point for all of those dimensions before data ever enters the target schema.

Null Substitution

A null in a required field means the downstream application cannot rely on that column. Two strategies exist: reject the row entirely, or substitute a configured default value. Which strategy you apply depends on the business rule in the data dictionary. For example, a `customer_region` field might allow a default of `'UNKNOWN'` so the record is not lost, while a `transaction_amount` field with a null must be rejected because no safe default exists. Always read the data dictionary before writing substitution logic. Hard-coding defaults in the script body rather than a configuration section makes the script brittle and harder to audit.

Data-Type Casting

Source systems frequently store numbers as strings and dates in whatever format the original developer chose. Before a row can be loaded into a typed relational column, every value must be cast to the correct type. In Python with pandas, `pd.to_numeric()` with `errors='coerce'` converts a column to float and sets unconvertible values to `NaN`, which you can then catch as a validation failure. For date columns, `pd.to_datetime()` with a `format` parameter and `errors='coerce'` performs the same service. After casting, rows where coercion produced `NaN` in a non-nullable column must be logged and rejected — not silently dropped.

ISO 8601 Date Standardization

Date formats in source data are notoriously inconsistent: `01/15/2024`, `2024-01-15`, `15-Jan-24`, and `January 15, 2024` all represent the same day. ISO 8601 (`YYYY-MM-DD`) is the international standard and the format most relational databases accept unambiguously. Once a date column is successfully cast to a pandas `datetime64` type, calling `.dt.strftime('%Y-%m-%d')` produces the correct string representation for export. If the cast fails, the row is rejected with reason code `INVALID_DATE`.

Deduplication

A primary key uniquely identifies each row in the target table. If the staging file contains two rows with the same primary key, loading both violates the constraint and will cause a database error or silent data overwrite, depending on the load strategy. Deduplication logic must decide which copy to keep — typically the first occurrence or the most recently timestamped — and must log all discarded duplicates with reason code `DUPLICATE_PK`. In pandas, `DataFrame.duplicated(subset=['primary_key_column'], keep='first')` identifies the rows to reject.

Business-Rule Filters

Beyond structural cleaning, most pipelines enforce domain-specific constraints. Examples include:

Each violated rule produces a rejected row with a specific reason code such as `OUT_OF_RANGE` or `MISSING_SHIP_DATE`. Reason codes must match the codes defined in the data dictionary so that downstream data-quality reporting is consistent.

Error Logging

Every rejected row must be written to a separate error file — not deleted silently. The error file should contain at minimum: the original row data, the reason code, and ideally the row number from the source file. This audit trail is essential for compliance, for root-cause analysis, and for returning bad records to the source system for correction. In a production environment, silent data loss is a data governance failure. DAMA DMBOK2 Chapter 13 treats traceability of rejected records as a core data quality practice.

Validation and the Rejection-Rate Threshold

After your transformation script runs, the instructor-provided validation script checks the clean output file against the target schema and counts violations. Your goal is zero schema errors. The rejection rate — rejected rows divided by total input rows — must also fall at or below the instructor-specified threshold (five percent for this lab). A rate above that threshold suggests either a systemic defect in the source data that must be escalated, or a bug in your transformation logic that is incorrectly rejecting valid rows. Investigate both possibilities before resubmitting.

Safe Lab Practices

Although this is a software lab with no electrical or mechanical hazards, safe data handling practices apply. Never write transformation output to the same file path as your input; a script error could truncate the original staging file, which you cannot recreate. Work on a copy of the instructor CSV, keep the original read-only. Commit your script to version control (or save numbered versions) before each test run so you can roll back a change that worsens results. Treat the data dictionary as authoritative — do not invent business rules not specified there.

Iteration is Normal

Professional ETL developers rarely produce a passing transformation script on the first run. Read the validation output carefully, trace each class of error back to the relevant section of your script, fix one category at a time, and re-run. Systematic iteration is faster than random edits.

Key terms10

ETLExtract, Transform, Load — a data integration pattern in which data is pulled from a source, cleaned and reshaped, and written to a target system such as a data warehouse or relational database.
Null substitutionReplacing a missing (null) value in a required field with a configured default value, as specified by the data dictionary, so the row is not rejected when the field cannot be left empty.
Data-type castingConverting a value from its source representation (often a string) to the correct data type required by the target schema, such as converting '42.5' to a float or '2024-01-15' to a date.
ISO 8601An international standard for representing dates and times; the date format YYYY-MM-DD is the most widely used form in database and data exchange contexts.
DeduplicationThe process of identifying and removing or logging rows that share the same primary key value, ensuring that the target table's uniqueness constraint is not violated.
Reason codeA short, standardized label attached to each rejected row in the error log that identifies the specific rule the row violated, such as DUPLICATE_PK or OUT_OF_RANGE.
Rejection rateThe proportion of input rows that were removed from the clean output and written to the error log, calculated as rejected rows divided by total input rows, often expressed as a percentage.
Data dictionaryA reference document that defines each column in a dataset: its name, data type, allowed values, nullability, and any business rules that apply, serving as the authoritative specification for transformation logic.
Business ruleA domain-specific constraint that data must satisfy beyond basic structural requirements, such as a numeric field that must be positive or a conditional requirement that one field be populated when another has a specific value.
Staging areaA temporary storage location, such as a flat file or database schema, where raw extracted data is held before transformation and loading; it isolates source data from the target system.

Worked examples4

1. A staging CSV has 200 rows. After transformation, 8 rows are written to the error log. Calculate the rejection rate and determine whether it meets the 5% threshold.
  1. Identify the total input rows: 200.
  2. Identify the rejected rows: 8.
  3. Calculate rejection rate: 8 ÷ 200 = 0.04.
  4. Convert to percentage: 0.04 × 100 = 4.0%.
  5. Compare to threshold: 4.0% ≤ 5.0%, so the threshold is met.
Answer: The rejection rate is 4.0%, which is at or below the 5% threshold. The file passes the rejection-rate check.
2. A staging CSV has 150 rows. After transformation, 12 rows are rejected. Calculate the rejection rate and determine whether it meets the 5% threshold.
  1. Identify the total input rows: 150.
  2. Identify the rejected rows: 12.
  3. Calculate rejection rate: 12 ÷ 150 = 0.08.
  4. Convert to percentage: 0.08 × 100 = 8.0%.
  5. Compare to threshold: 8.0% > 5.0%, so the threshold is NOT met.
Answer: The rejection rate is 8.0%, which exceeds the 5% threshold. The script must be reviewed — either the source data has a systemic defect or the transformation logic is incorrectly rejecting valid rows.
3. A column contains the date string '15-Jan-2024'. Show the steps to standardize it to ISO 8601 format YYYY-MM-DD.
  1. Parse the source string using the format specifier '%d-%b-%Y', which matches day-abbreviatedMonth-4-digit-year.
  2. Confirm the parsed date components: day = 15, month = January (01), year = 2024.
  3. Reformat using strftime with the target format '%Y-%m-%d'.
  4. Result: '2024-01-15'.
Answer: The standardized ISO 8601 date is 2024-01-15.
4. A required numeric column 'unit_price' has the business rule: value must be greater than 0 and less than or equal to 9999.99. A row contains the string value '10500'. Determine what transformations apply and what should happen to this row.
  1. Cast '10500' to a numeric type: it converts successfully to the integer 10500 (or float 10500.0), so no INVALID_TYPE rejection applies.
  2. Apply the business rule: 10500.0 > 9999.99, so the value is out of the allowed range.
  3. The row must be rejected and written to the error log.
  4. Assign reason code OUT_OF_RANGE to the error log entry for this row.
Answer: The row is rejected with reason code OUT_OF_RANGE. The value 10500 exceeds the maximum allowed value of 9999.99 for the unit_price column.

The math in this lesson1

Learners compute an ETL rejection rate as a percent and compare it to a 5% threshold.
7.RP.3
Brush up in the math halls at newSchoolWorks.com:
In class: Receive a dirty staging CSV containing nulls, mixed date formats, duplicate primary keys, and out-of-range numeric values; write a Python transformation script that applies each rule and logs every rejected row to a separate error file with a reason code. · Use pandas (or plain Python dicts, instructor's choice by lab cohort) to cast columns to correct data types, standardize all dates to ISO 8601 (YYYY-MM-DD), and substitute a configured default value for nulls in required fields. · Run the instructor-provided validation script against the clean output file and iterate on the transformation script until the validation script reports zero schema violations and a rejection rate at or below the instructor-specified threshold.
Materials: Student laptops, Python 3, pandas library, instructor-prepared dirty CSV dataset, instructor-provided validation Python script, data dictionary specifying target schema and business rules, DAMA DMBOK2 Chapter 13 excerpt (data quality)
Check: Clean output file passes the instructor validation script with zero schema errors and a row-rejection rate at or below 5%; error log correctly documents every rejected row with a reason code; pass = both criteria met

Practice check8

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

Data Quality and ETL (DAMA CDMP / DMBOK2 Chapter 13)
1. In a Python transformation script, a date column contains the value '31-Dec-2023'. After calling pd.to_datetime() with errors='coerce' and an incorrect format string, the result is NaT. What is the correct next step?
Data Quality Metrics (DAMA CDMP)
2. A staging dataset has 400 rows. The transformation script rejects 22 rows. What is the rejection rate, and does it pass a 5% threshold?
Data Standards and Interoperability (DAMA CDMP / DP-300 / Oracle DBA)
3. Which ISO 8601 date format should all date columns be standardized to when producing the clean output file for this lab?
Relational Database Integrity (Oracle DBA CA / PostgreSQL CE / DP-300)
4. A staging file contains two rows with the same primary key value. The transformation script keeps the first occurrence. What reason code and action should be applied to the second row?
Data Quality / Business Rules (DAMA CDMP)
5. The data dictionary states that the 'customer_region' column is required but may use the default value 'UNKNOWN' when null. The 'transaction_amount' column is required and has no permitted default. A row arrives with both fields null. What is the correct transformation outcome?
Data Governance and Quality (DAMA CDMP)
6. Why must every rejected row be written to an error log file rather than simply deleted from the pipeline?
ETL Development / Python (PostgreSQL CE / DP-300 / Oracle DBA CA)
7. A business rule states that the 'order_status' field value 'SHIPPED' requires a non-null 'ship_date'. A row arrives with order_status = 'SHIPPED' and ship_date = null. Which pandas approach best identifies this row for rejection?
Safe Data Handling / Lab Practices
8. Before beginning a transformation lab session, a student should take which of the following precautions to protect the original staging CSV?
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.