Data validation and transformation
Practical guide to checking data quality (validation) and converting data into forms BI systems can use (transformation), including definitions, common checks, algorithms, syntax to remember and exam-style worked examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Two sentences: Engineers use data validation and transformation to make raw data reliable and fit for Business Intelligence (BI) analytics and reporting. Good validation and transformation prevent wrong conclusions, broken dashboards and wasted compute time in downstream systems such as data warehouses and OLAP cubes.
Key ideas
Start with definitions (each term is defined before use):
- Data: raw facts and measurements (numbers, text, timestamps) collected from systems or users.
- Data validation: the set of checks that decide whether a data item is acceptable according to rules (type, range, format, referential integrity). Validation can reject, flag, or route bad records.
- Data transformation: changing data into a new form needed by analysis or storage (type conversion, normalization, encoding, aggregation). Transformations must preserve meaning or document changes.
- ETL (Extract, Transform, Load): a pipeline style where data is extracted from sources, transformed, then loaded into target storage (data warehouse). Assumes transform before load.
- ELT: Extract, Load, Transform — extract and load first, then transform inside the target system (common with modern cloud warehouses).
- Schema: the structure (columns, types, constraints) that data must match.
- Constraint: a rule on data (e.g., column must be integer, value within [0,100], unique key).
- Imputation: filling missing values using a strategy (mean, median, mode, forward-fill, model-based).
- Normalization (min-max): rescaling numeric values to a fixed range, usually [0,1].
- Standardization (z-score): converting values to have mean 0 and standard deviation 1.
- Encoding: converting categorical strings to numeric codes (label encoding, one-hot encoding).
- Deduplication: finding and merging duplicate records (exact or fuzzy matches).
- Referential integrity: when one table references keys in another, the referenced keys must exist.
Important data quality dimensions (define each):
- Accuracy: values reflect real-world truth.
- Completeness: no missing values where data is required.
- Consistency: no conflicting values across datasets.
- Validity: values conform to allowed formats and ranges.
- Uniqueness: absence of duplicate records.
- Timeliness: data is up-to-date for the intended use.
Validation checks — exact statements of rules you will apply in practice:
- Type check: value's data type equals required type (e.g., string, integer, date). If input cannot be parsed to the required type it fails validation.
- Range check: numeric value v passes if lower ≤ v ≤ upper. State bounds.
- Format check: value matches a regular expression pattern (e.g., phone number). Use anchored patterns that match the whole field.
- Uniqueness check: key column values are all distinct.
- Referential check: for every foreign key fk in table A, there exists a primary or unique key pk in table B such that fk = pk.
- Business rule check: domain-specific rule, e.g., order_date ≤ delivery_date.
Design of a simple ETL validation stage (diagram description for exam): draw five boxes left to right labeled: Source Systems -> Extract -> Validate -> Transform -> Load (Data Warehouse). Between Extract and Validate draw an arrow. Under Validate list checks: type, range, format, referential. Under Transform list: cast types, impute, encode, normalize, aggregate. Label arrows with actions.
Assumptions commonly used in exam problems: missing values are independent (MCAR) unless stated otherwise; when asked to impute with mean/median you assume these are acceptable; when normalizing use min-max computed on training set in predictive scenarios.
Formulas
mean x̄ = (1/n) · Σ_{i=1..n} x_i — x̄ is the sample mean of values x_i, unit same as x_i. Use when imputing by mean or computing z-score.
median = middle value of sorted x_i — unit same as x_i. Use when imputing robustly against outliers.
std s = sqrt( (1/(n-1)) · Σ_{i=1..n} (x_i - x̄)^2 ) — s is sample standard deviation, unit same as x_i. Use in z-score.
z = (x - x̄) / s — z is a dimensionless standardized value (number of standard deviations from the mean), applies when s ≠ 0.
minmax_scaled = (x - min_x) / (max_x - min_x) — rescales to [0,1] when max_x ≠ min_x.
clip(x; a, b) = max(a, min(b, x)) — value clipped to [a,b].
Syntax to remember (common SQL and Python/pandas):
- SQL:
CAST(column AS INTEGER),COALESCE(column, default),UPDATE table SET col = value WHERE condition,SELECT * FROM table WHERE column REGEXP 'pattern'(MySQL) orREGEXP_LIKE(column, 'pattern')(Oracle/MySQL 8.0+); in PostgreSQL usecolumn ~ 'pattern'orREGEXP_MATCHES(column, 'pattern'). - Pandas (Python):
df['col'].astype(int),df['col'].fillna(df['col'].median()),pd.get_dummies(df['cat']),df['col'] = (df['col'] - df['col'].min()) / (df['col'].max() - df['col'].min()),df.drop_duplicates(subset=['key']),df['col'] = df['col'].clip(lower, upper). - Regular expression note: anchor full-match with
^and$when checking whole field.
Worked examples
Example 1 — Numerical column cleaning, imputation and normalization (step-by-step): Data: ages column in years from 6 records: ["25", "30", "", "27", "999", "29"] where empty string means missing and 999 is an obvious outlier. Steps:
- Type conversion: parse strings to numbers; missing stays as null. After parse: [25, 30, null, 27, 999, 29].
- Range check: business rule says valid ages ∈ [15, 100]. Check values: 999 fails range and will be treated as outlier/invalid.
- Decide strategy: replace invalid/outlier with median of valid values; treat missing similarly.
- Compute median of valid values (excluding null and 999): sorted valid = [25,27,29,30] so median = (27+29)/2 = 28. Formula used: median. Show calculation explicitly.
- Impute missing and invalid with median 28: result = [25, 30, 28, 27, 28, 29].
- Min-max normalize to [0,1]: min_x = 25, max_x = 30. Apply
minmax_scaled = (x - 25)/(30-25). Calculations:- 25 -> (25-25)/5 = 0.0
- 30 -> (30-25)/5 = 1.0
- 28 -> (28-25)/5 = 3/5 = 0.6
- 27 -> 2/5 = 0.4
- 28 -> 0.6
- 29 -> 4/5 = 0.8 Final normalized column (bold): [0.0, 1.0, 0.6, 0.4, 0.6, 0.8].
Example 2 — Categorical cleaning, deduplication and encoding (algorithm trace): Input small customer table (rows numbered):
- {cust_id: 1001, name: "Ravi Kumar", phone: "+91-9876543210"}
- {cust_id: 1002, name: "R. Kumar", phone: "9876543210"}
- {cust_id: 1003, name: "Anita Sharma", phone: ""}
- {cust_id: 1004, name: "Anita Sh.", phone: "9123456780"}
Steps:
A) Normalize phone format (remove non-digits, ensure 10 digits or add +91 if missing):
- Row1 phone -> digits 919876543210 -> last 10 digits 9876543210 stored as +91-9876543210.
- Row2 phone -> 9876543210 -> +91-9876543210.
- Row3 phone -> missing.
- Row4 phone -> 9123456780 -> assume +91-9123456780. B) Exact dedup by phone: rows 1 and 2 now share phone +91-9876543210. Merge duplicates: keep earliest cust_id 1001, combine other fields (store alternate names in alias list). After dedup table becomes: A) {cust_id:1001, name:"Ravi Kumar", alias:["R. Kumar"], phone:+91-9876543210} B) {cust_id:1004, name:"Anita Sh.", alias:[], phone:+91-9123456780} C) {cust_id:1003, name:"Anita Sharma", alias:[], phone:""} C) Encode a category 'has_phone' as 1 if phone present else 0: record A -> 1, record B -> 1, record C -> 0. D) One-hot encode nothing else here; final output ready for load. This trace shows practical rules: normalization of formats, deterministic dedupe by normalized key, and simple encoding.
Example 3 — Model short-answer (theory): Question: "Explain three strategies to handle missing values and give when each is appropriate." Model answer (points to include for full marks): define missingness types (MCAR, MAR, MNAR), then give strategies: delete rows (when small % missing and MCAR), impute by mean/median/mode (simple, when distribution symmetric or robust median if skewed), model-based imputation (predictive models or k-NN) for complex patterns, forward/backward-fill for time series, and mention bias risks.
Common mistakes
- Using the same normalization parameters (min, max, mean, std) computed on full dataset when building predictive models; you must compute these on training set and apply to test set.
- Losing original data: overwriting raw source before validation makes audits impossible. Always keep a copy of raw data.
- Forgetting to check referential integrity: loads that ignore foreign keys create orphan records.
- Using one-hot encoding with very high-cardinality categorical columns without dimensionality reduction leads to huge tables.
For your exam
Kinds of questions you will see: definition questions (define data validation, ETL, imputation), short notes (compare ETL vs ELT, list validation checks), derivations (show z-score formula and compute standard deviation), numericals (clean a numeric column and normalize it), programs or pseudo-code (write SQL or pandas steps to validate and transform), diagrams (draw an ETL validation stage). What full-marks answers include:
- Clear definitions of each bolded term used.
- Explicit assumptions (e.g., how you treat missing data, MCAR/MAR/MNAR if relevant).
- Step-by-step operations with intermediate results (for numericals or traces), and final values boxed or bolded.
- Correct syntax snippets if asked for SQL/pandas, and explanation of why each step is necessary.
- For diagrams, labels on boxes and arrows and a short explanation of each component.
Quick check
- Define imputation in one line.
- Write the formula to standardize x to z-score.
- Which validation check detects duplicate primary keys?
Answers: imputation = filling missing data values using a chosen method (mean/median/mode/model-based);
z = (x - x̄) / swhere x̄ is sample mean and s is sample standard deviation; uniqueness (or uniqueness/duplicate check) detects duplicate primary keys.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?