Full answer
Pipeline:
- Staging: load raw text into
staging_orderswith permissive TEXT columns, so the load itself never fails halfway. - Validate with queries, for example:
- required fields:
WHERE order_id IS NULL OR trim(order_id) = '' - types: values that do not look like integers or dates
- references:
customer_idvalues with no matching customer - duplicates within the file and against existing rows
- required fields:
- Reject: insert failing rows into
import_rejects(row_no, reason, raw)and report counts. - Publish:
INSERT INTO orders SELECT ... FROM staging_orders WHERE validinside a transaction; if the reject rate passes a threshold, abort the whole batch instead. - Constraints (NOT NULL, CHECK, foreign keys, unique keys) on
ordersstop anything the checks missed.
Keeping the raw file and the batch id on imported rows makes it possible to undo a bad import precisely.
Key points
- Stage raw data first
- Validate with SQL checks
- Record rejects with reasons
- Publish valid rows in one transaction
- Constraints as the final guard
Common mistakes
- Loading directly into production tables
- Silently skipping bad rows without a report
Follow-ups
- How would you make the import idempotent?
- What reject rate should abort a batch?
Tips
- Describe staging then publish