SQL Data Cleansing Script for Construction Cost Code and Labor Records
Build a SQL script to sanitize, validate, and align construction timesheet entries with MasterFormat cost codes.
Use this template when subcontractor timesheets and job-costing entries have invalid dates, incorrect CSI codes, or negative hours. It creates a robust SQL cleaning pipeline that normalizes data prior to ERP cost synchronization.
Role: Lead Construction Analytics Engineer specializing in ERP job-costing data integrity.
Context
- Staging Timesheet Table: {{raw_timesheet_table}}
- Canonical Cost Code Table: {{master_cost_code_table}}
- Source Date Format Variations: {{date_format_variance}}
- Missing Worker ID Handling: {{null_handling_mode}}
- Max Labor Hours Threshold: {{error_flagging_threshold}}
- Target Validated Table: {{validated_table_name}}
Task
Generate an idempotent ANSI SQL transformation script to clean, validate, and standardize messy subcontractor timecard logs from {{raw_timesheet_table}}, cross-referencing CSI codes against {{master_cost_code_table}}, enforcing hours sanity checks using {{error_flagging_threshold}}, and populating {{validated_table_name}}.
Method
- Create staging Common Table Expressions (CTEs) that cast and sanitize raw text columns from {{raw_timesheet_table}}.
- Parse non-standard date entries matching patterns in {{date_format_variance}} into standard ISO 8601 date timestamps.
- Normalize cost code strings by stripping non-alphanumeric noise and validating against {{master_cost_code_table}}.
- Apply rule-based resolution for missing worker identifiers following the {{null_handling_mode}} policy.
- Flag or clip anomalous work-shift entries exceeding {{error_flagging_threshold}} hours in a single 24-hour window.
- Standardize trade classification codes, upper-casing craft names and trimming whitespace.
- Insert clean records into {{validated_table_name}} while routing rejected records to an audit table with explicit rejection reason codes.
Constraints
- The SQL script MUST be deterministic and safe to re-run (idempotent) using transactions.
- The script MUST NOT delete unparseable rows; invalid rows must be inserted into an audit quarantine table.
- Use standard ANSI SQL compatible with modern data warehouses (PostgreSQL/Snowflake/BigQuery).
- Include explicit comments before each CTE explaining the transformation rule.
Output format
Provide the solution as a single structured SQL file containing:
- Header comment detailing source tables, assumptions, and validation logic.
- DDL statements ensuring {{validated_table_name}} and quarantine tables exist.
- Main transformation query organized as readable CTEs ending with an
INSERT INTO ... SELECTstatement. - Post-execution verification queries that report row counts and error breakdown.
Self-review
- Check that all variables ({{raw_timesheet_table}}, {{master_cost_code_table}}, {{date_format_variance}}, {{null_handling_mode}}, {{error_flagging_threshold}}, {{validated_table_name}}) are integrated.
- Ensure timestamp conversions handle leap years and time zone shifts without throwing fatal query errors.
- Verify that foreign key mismatches with {{master_cost_code_table}} are caught gracefully.
Explicit role, a named task, and discrete steps the model can follow.
Background, inputs and variables the model needs before it starts.
Hard boundaries — what the model must and must not do.
A named, field-level shape for the response.
Ordered work items that force analysis before an answer.
Length and structure that travel across frontier models.
Signal density — instruction weight without padding.
Documented variables so the scaffold adapts to new inputs.
Quality bar, assumptions and behaviour when inputs are thin.
How much real usage the template has behind it.