Comprehensive Guide to SQL Data Profiling, HIPAA De-Identification Architectures, and Automated ETL Pipelines

Course Roadmap and Curriculum Sequencing

  • Current academic progression sits at Week 1010.

  • Week 1111 concludes SQL instruction with Data Control Language (DCL):

    • Core focus includes database security, creating user roles, establishing user groups, assigning system privileges, and securing database architectures.

    • An asynchronous video walkthrough for Homework 33 will be provided.

  • Post-SQL curriculum transition:

    • Thursday of Week 1111 introduces foundational data analytics concepts without hands-on programming.

    • Subsequent coursework transitions directly into data visualization utilizing Tableau.

    • Following Tableau, instruction advances into Python for data engineering and analysis.

Data Quality Auditing and Statistical Profiling

  • Fundamental stages of data quality improvement begin with a comprehensive data quality audit.

  • Statistical profiling of data fields requires analyzing:

    • Allowable values and domain completeness.

    • Identification of representational discrepancies where identical real-world entities appear as multiple disparate entries due to inconsistent formatting or nomenclature.

    • Summation and aggregation of all field values.

    • Analysis of structural patterns, value distributions, frequency metrics, and outliers.

  • Nature and operational definition of outliers:

    • An outlier is not inherently erroneous data; it denotes an observation falling substantially outside the expected statistical distribution or reference threshold.

    • An individual weighing 300 lbs300\,\text{lbs} represents an extreme yet physiologically valid outlier; an entry of 3000 lbs3000\,\text{lbs} represents corrupted data.

    • An executive salary of \n$20{,}000{,}000\n within a corporate compensation schema represents a statistically extreme outlier, yet constitutes legitimate organizational data for a Chief Executive Officer.

PostgreSQL Session Context and Search Paths

  • Working across distinct database schemas typically demands explicit object dot notation (e.g., homework3.table_name or ident.patients).

  • The SET search_path TO <schema_name>; command alters the active namespace resolution path within PostgreSQL:

    • Executing SET search_path TO ident; instructs the query execution engine to prioritize the ident schema when unqualified table names are invoked.

    • Contextual scope: Search path modifications apply strictly to the specific active query editor window or active session; parallel open editor windows remain unaffected.

    • Session persistence: The configuration is strictly transient. Terminating a connection or closing the query window resets the search path to default (public). Failure to re-execute the statement on reconnect yields relation does not exist errors.

    • Cross-schema execution: Setting a search path simplifies single-schema operations, but inter-schema pipeline transformations still necessitate qualified dot notation (e.g., targeting deident.table while reading from the path-scoped ident).

Attribute Domain Analysis and Standardization

  • Clinical and Administrative Database Entities Examined:

    • patients: Baseline demographic and operational identification data.

    • encounters: Longitudinal healthcare visits, inpatient/outpatient interactions, vital signs, and encounter timings.

    • diseases: Diagnosis records mapped to specific encounter instances.

    • disease_types: Standardized diagnostic classification dictionary containing master terminology codes.

  • Profiling Categorical Domains:

    • Domain analysis inspects the discrete set of all permitted values within a given column.

    • Profiling the religion attribute in the identified dataset:

    • Records demonstrate consistent uppercase casing throughout.

    • Absence of outright typographical and spelling corruptions.

    • Identification of missingness: NULL appears as an explicit category (occupying index row 1414 in testing).

    • Granularity evaluation: Domain contains a mixture of high-level religious groupings and specific intra-faith denominations, requiring future grouping into standardized super-categories.

    • Visualization formatting: The SQL INITCAP(column_name) function converts uppercase text into title casing (e.g., aliased as religion_display) for automated consumption in reporting layers and Tableau dashboards.

    • Profiling the department_name attribute:

    • Exhibits 3232 distinct departmental values without default title capitalization (e.g., ambulatory surgery, anesthesiology).

    • Spatial hierarchy considerations: Medical facilities frequently organize departments across physical infrastructure (e.g., North Tower, South Tower, specialized functional units).

    • Missing departmental attributes often require exporting distinct domains into external spreadsheets for domain experts to enrich with unit-level hierarchical metadata before reloading.

  • Case Study on Clinical Free-Text Capture Failures:

    • A nationwide nursing workforce reporting system spanning numerous healthcare organizations (including ECU Health) allowed unconstrained free-text data entry for hospital department reporting.

    • Personnel populated fields with localized physical shorthand (e.g., "2 North", "7 West", "East Tower"), necessitating researchers to manually procure architectural facility blueprints to deduce clinical specialties.

    • Over 40004000 distinct text permutations existed for a single occupational department variable.

    • The acronym NICU appeared under dozens of variants, including "NICU", "neonatal ICU", "neonatal neonatal intensive care unit", over 2525 phonetic misspellings, and erratic capitalization.

    • Interface design principle: Data architecture must enforce constrained drop-down menus derived from controlled vocabularies. If an "Other" field is retained, administrative auditing must periodically scrub and promote frequent recurring selections into formalized drop-down domain options.

Frequency Profiling and Temporal Analysis of Data Anomalies

  • Frequency Counts and Positional Shorthand in SQL:

    • Distribution analysis utilizes standard GROUP BY aggregations.

    • Positional indexing: SQL implementations allow referring to projected columns by their numerical ordinal position (e.g., GROUP BY 1 ORDER BY 2 DESC), referencing column 11 and column 22 respectively due to SQL's 11-based indexing design.

    • Aggregating the religion attribute yields sample distributions such as 3939 NULL records, 1919 NO PREFERENCE, and 1212 CATHOLIC.

  • Longitudinal Profiling of Departmental Completeness:

    • Combining frequency counts with temporal boundary analysis (MIN(encounter_date) and MAX(encounter_date)) reveals both usage volume and operational lifecycles.

    • Identifying critical data defects: Encounter analysis revealed 15731573 records possessing a NULL department designation.

    • Temporal bounding indicates encounters span from 19831983 through 20102010.

    • Determining error persistence:

    • Evaluating whether the maximum error timestamp coincides with the terminal boundary of the database (20102010) determines if an ingestion defect is actively persisting or historically resolved.

    • If the maximum database date is current (e.g., 20262026) and the final NULL occurred in 20102010, the issue represents an extinguished legacy bug requiring lower remediation urgency.

    • Active anomalies necessitate technical backfilling (inferring locations via specialized facility codes, billing data, diagnostic codes, or procedure codes) alongside administrative data collection policies.

Parametric Outlier Detection and SQL-Based Histograms

  • Outlier Profiling via Central Tendency and Dispersion:

    • Baseline patient age profiling reveals a minimum age of approximately 88, a maximum of 9393, and an arithmetic mean of 4949, establishing reasonable clinical bounds.

    • Measure of central tendency: Arithmetic mean (μ\mu).

    • Measure of dispersion: Standard deviation (σ\sigma).

    • Population versus sample standard deviation:

    • Population parameter (stddev_pop\text{stddev\_pop}) employs denominator NN.

    • Sample statistic (stddev_samp\text{stddev\_samp} or generic stddev\text{stddev}) employs denominator N−1N - 1.

  • Computing Dispersion Across Aggregated Encounter Counts:

    • To calculate dispersion over department encounters, an inner query calculates individual department frequencies, followed by an outer query calculating metrics over the derived table:

    • Department count mean (μ\mu): 13.713.7.

    • Department count standard deviation (σ\sigma): 16.116.1.

    • Extreme variability indication:

    • Standard deviation exceeds the mean (16.1>13.716.1 > 13.7).

    • Evaluating μ−1σ\mu - 1\sigma yields 13.7−16.1=−2.413.7 - 16.1 = -2.4. Because encounter counts cannot assume negative integers, the lower tail is truncated at zero, exhibiting a heavily right-skewed distribution.

  • Threshold-Based Upper-Tail Outlier Isolation:

    • Establishing an outlier threshold at two standard deviations above the mean (μ+2σ\mu + 2\sigma):

    • In a normal distribution, within ±2σ\pm 2\sigma bounds represents approximately 95.4%95.4\% of a two-tailed distribution, or 97.8%97.8\% in a one-tailed evaluation, leaving an extreme probability tail of 2.2%2.2\%.

    • For comparative rigor: Industrial Six Sigma targets 6σ6\sigma (permitting roughly 0.00034%0.00034\% defect rates), whereas aerospace organizations such as NASA regularly adopt 5σ5\sigma thresholds for statistical significance.

    • Computing the cutoff threshold:     Cutoff=μ+2σ=13.77+2(16.17)=46.11\text{Cutoff} = \mu + 2\sigma = 13.77 + 2(16.17) = 46.11

    • Applying a one-tailed query filter seeking departments where count≥46.12\text{count} \ge 46.12 (effectively ≥47\ge 47 visits) isolates two departments: General Care and Student Health.

    • Contextual verification: For an academic medical center, elevated volumes in general care and student health reflect logical operational realities rather than data corruption.

  • ASCII Histogram Construction in SQL:

    • Constructing in-console horizontal bar charts utilizes SQL string padding functions.

    • Left-padding (LPAD(string, total_length, pad_character)) and Right-padding (RPAD):

    • Primary engineering utility: Restoring missing leading zeros to fixed-width identifiers, such as truncated four-digit New England ZIP codes or standardized Federal Information Processing Standards (FIPS) county codes.

    • Histogram generation: Passing an empty string with a targeted column count generates a repeating sequence of characters:       LPAD('', COUNT(*), '#')

    • Formatting constraints:

    • Continuous numeric measures (such as decimal ages like 8.1024988.102498) must be explicitly cast to integers to prevent excessive single-row granularity.

    • Horizontal bar lengths can be scaled via integer division (e.g., COUNT(*) / 2 to represent a 2:12:1 ratio) to prevent terminal text-wrapping in high-volume tables.

    • Binned age distribution profiles reveal volume concentrations peaking around ages 5151 and 5252.

HIPAA Privacy Rule and De-Identification Standards

  • Health Insurance Portability and Accountability Act (HIPAA) Privacy Rule stipulates two methodologies to achieve legal de-identification:

    • Expert Determination Method:

    • Involves applying statistical and scientific principles by a qualified expert.

    • Requires proving the statistical risk of anticipated recipients identifying an individual is very small.

    • High computational complexity: Appending a single new row of clinical data can invalidate mathematical risk models.

    • Safe Harbor Method:

    • Prescribes the complete removal of 1818 enumerated direct and quasi-identifiers.

    • Produces a universally recognized de-identified dataset, or a limited dataset for research if specified geographic and temporal variables are partially retained under data use agreements.

  • The 18 Enumerated Safe Harbor Identifiers:

    • Names (first, middle, last, aliases).

    • All geographic subdivisions smaller than a state (street address, city, county, precinct, physical address):

    • ZIP Code Exception: The initial three digits of a five-digit ZIP code may be retained if, according to publicly available Census data, the aggregate population within all ZIP codes sharing that identical three-digit prefix exceeds 20,00020{,}000.

    • If the cumulative population sharing the three-digit prefix is ≤20,000\le 20{,}000, the prefix must be masked to 000 (represented as 000XX or 00000).

    • Example: Prefix 278 encompassing ZIP codes 27858 and 27834 evaluates combined population against the 20,00020{,}000 individual floor.

    • All elements of dates (except year) directly related to an individual:

    • Includes birth dates, hospital admission dates, discharge dates, and dates of death.

    • Strict Age Ceiling Constraint: All individual ages exceeding 8989 years (≥90\ge 90) and all elements of dates indicative of such ages must be aggregated into a single open-ended category of 90 or older90\,\text{or older}.

    • Evaluated against a reference operational year, individuals born in or prior to 19361936 must be categorized as ≤1936\le 1936.

    • Telephone numbers.

    • Fax numbers.

    • Electronic mail addresses.

    • Social Security Numbers (SSN).

    • Medical Record Numbers (MRN).

    • Health plan beneficiary numbers.

    • Financial and administrative account numbers.

    • Certificate and professional license numbers.

    • Vehicle identifiers and serial numbers, including motor vehicle license plate numbers.

    • Medical device identifiers and equipment serial numbers.

    • Web Universal Resource Locators (URLs).

    • Internet Protocol (IP) address identifiers.

    • Biometric identifiers, including finger and voice prints.

    • Full face photographic images and any comparable identifiable images.

    • Any other unique identifying number, characteristic, or digital code.

ETL De-Identification Pipeline Architecture and Schema Design

  • Systematic Four-Step Extract, Transform, Load (ETL) Architecture:

    • Step 1: Initialize target destination schema (deident).

    • Step 2: Extract attributes from source schema (ident) and apply structural de-identification rules.

    • Step 3: Instantiate lookup mapping tables to generate and persist surrogate serial keys across all relational entities.

    • Step 4: Execute final transformational data loading into target storage schemas.

  • Relational Attribute Transformation Mapping:

    • Entity patients:

    • patient_id: Replaced with an anonymized, surrogate serial key.

    • first_name, middle_initial, last_name: Completely purged.

    • gender, race, religion, marital_status, language, occupation: Retained as-is (subject to auditing for rare identifying outlier values in occupation).

    • birth_date: Truncated to extract year; years evaluating to ≤1936\le 1936 masked to the literal string '<= 1936'.

    • street, city: Completely purged.

    • state, country: Retained as-is.

    • zip_code: Generalized via masking (e.g., 278XX or 000XX).

    • Entity disease_types:

    • disease_id: Retained without alteration (serves as a standardized medical dictionary code, possessing no individualized identification risk).

    • Associated descriptive classifications: Retained.

    • Entity encounters:

    • encounter_id: Replaced with an anonymized surrogate key.

    • patient_id: Replaced with the corresponding surrogate foreign key generated during patients transformation.

    • admit_date, discharge_date: Converted to admit_year and discharge_year (string-formatted to accommodate ≤1936\le 1936 bounds).

    • department_name: Retained as-is.

    • age: Values ≥90\ge 90 masked to text literal '>= 90'.

    • Clinical vital signs (systolic, diastolic, temperature, pulse, weight, height, respirations): Retained.

    • primary_disease_id: Retained (static dictionary reference).

    • Entity diseases:

    • encounter_id: Replaced with anonymized surrogate encounter foreign key.

    • disease_id: Retained.

    • weighting_factor: Retained as an invariant numeric factor.

  • Static Replacement versus Incremental Pipeline Loads:

    • Static loads drop the entire downstream schema (DROP SCHEMA ... CASCADE) and rebuild all entities from scratch; optimal for small-to-medium databases where delta computation risk exceeds compute overhead.

    • Incremental loads extract and transform strictly modified records (deltas); higher systemic complexity with risk of missing asynchronous upstream alterations.

  • Writing Idempotent Schema Automation Scripts:

    • Pipeline scripts must execute autonomously without raising fatal state-dependent syntax exceptions.

    • Initial schema teardown: DROP SCHEMA IF EXISTS deident CASCADE; prevents halting when the schema does not pre-exist, returning an informative system notice rather than an error.

    • Schema instantiation: CREATE SCHEMA IF NOT EXISTS deident; guarantees execution without duplication collision.

  • The Data Type Trap with Masked Values:

    • In standard relational design, age and birth_year default to INTEGER or NUMERIC data types.

    • Incorporating HIPAA masking rules (≤1936\le 1936 or ≥90\ge 90) forces the insertion of character-based string literals (e.g., '<= 1936').

    • Columns storing masked ages or years must be altered to TEXT or VARCHAR during Data Definition Language (DDL) table instantiation.

    • Analytical trade-off: Transforming numerical measurements into string values permanently strips the database engine's capacity to compute direct aggregations (such as arithmetic averages via AVG(age)) without complex conditional parsing.

  • Longitudinal Re-Identification Vulnerabilities in Safe Harbor Data:

    • Safe Harbor evaluates data rows in static isolation rather than across longitudinal release versions.

    • In year one, an 8989-year-old patient displays an explicit birth year of 19351935.

    • In year two, the identical patient turns 9090, masking their birth year to '<= 1936'.

    • Analysts possessing sequential database releases can cross-reference longitudinal snapshots to circumvent Safe Harbor protections and infer exact ages.

Surrogate Key Generation, Sequencing, and Transformation Logic

  • Mapping Table Architecture for Surrogate Keys:

    • Anonymization requires decoupling operational primary identifiers from downstream analytic consumers while preserving relational integrity across foreign keys.

    • A surrogate key map table (patient_ids) is structured with two attributes:

    • patient_id INT PRIMARY KEY: Captures identified operational identifiers directly from the source table.

    • patient_id_deident SERIAL: PostgreSQL sequence-backed integer automatically generating consecutive surrogate values.

    • Inline primary key declarations enforce unique constraints, preventing duplicate source insertions that would otherwise generate multiple surrogate identifiers for a single patient.

  • Database State Terminology: Upserts versus Instates:

    • Operational database pipelines manage data collisions using conditional execution statements:

    • Upsert (Update / Insert): Attempts an UPDATE; upon finding no matching record (failure), it executes an INSERT.

    • Instate (Insert / Update): Attempts an INSERT; upon encountering a unique constraint violation (failure), it executes an UPDATE.

    • Operational performance selection:

    • When adding 10001000 records where 900900 are entirely new, an Instate maximizes throughput because 90%90\% of executions succeed on the first attempt without throwing execution exceptions.

    • When updating existing systems where new additions represent a small fraction, an Upsert minimizes transaction overhead.

  • Internal Mechanics of PostgreSQL Sequences (SERIAL):

    • Assigning a SERIAL pseudotype instantiates an underlying sequence generator (nextval('patient_ids_patient_id_deident_seq'::regclass)).

    • Default configuration properties:

    • Increment value: 11.

    • Minimum value: 11.

    • Maximum value: System integer maximum (2,147,483,6472{,}147{,}483{,}647).

    • Cache allocation: 11.

    • Sequence customization: When merging disparate health systems, starting sequences at 11 creates key collisions. Sequence generators can be configured to begin at elevated initial offsets (e.g., system A starts at 11, system B starts at 100,001100{,}001 or 1,000,0011{,}000{,}001).

    • Cryptographic alternative: Where sequential surrogate keys leak temporal registration order, systems deploy Universally Unique Identifiers (UUIDs) or one-way cryptographic hashes.

  • Populating and Utilizing Identity Translation Maps:

    • Ingestion query: sql INSERT INTO deident.patient_ids (patient_id) SELECT patient_id FROM ident.patients ORDER BY patient_id; &nbsp;&nbsp;&nbsp;&nbsp;

  • Applying surrogate foreign keys to target entities requires joining the identified source data against the surrogate map via the original primary key: sql SELECT i.patient_id_deident, p.gender, p.race FROM ident.patients p JOIN deident.patient_ids i ON p.patient_id = i.patient_id; &nbsp;&nbsp;&nbsp;&nbsp;

  • Transforming Temporal Attributes via Conditional Casting:

    • Extracting parts of temporal types utilizes EXTRACT(field FROM source) (e.g., EXTRACT(YEAR FROM birth_date)).

    • Type consistency in conditional evaluations:

    • Attempting to return an integer in the ELSE branch while returning a string literal in the THEN branch raises a runtime syntax error: invalid input syntax for type numeric: "<= 1936".

    • SQL engines require unified data types across all possible conditional branches.

    • Resolved query using PostgreSQL explicit casting syntax (::TEXT): sql CASE WHEN EXTRACT(YEAR FROM birth_date) <= 1936 THEN '<= 1936' ELSE EXTRACT(YEAR FROM birth_date)::TEXT END AS birth_year &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Questions & Discussion

  • Course Logistics and Academic Scheduling Adjustments:

    • Query/Topic: Clarification regarding upcoming lecture scheduling, format changes, and morning session start times.

    • Response/Resolution: In-person class session scheduled for the following morning will shift start times from 09:0009:00 to 09:3009:30.

    • Reason: Personal medical appointment originally scheduled for 07:4507:45 was delayed by the healthcare provider to 08:1508:15, compressing morning transit time.

    • Protocol on Academic Waiting Periods:

    • Student remark noted the standard university "1515-minute rule" concerning class departures in the event of instructor absence.

    • Resolution: Formal notification provided that arrival will occur by 09:3009:30; students requested to remain in the classroom should minor traffic delays extend arrival slightly past 09:3009:30, with confirmation that email notifications will be distributed to students.