← Back to SQL, page 22

sql-0440 · Medium mid

A nightly CSV import sometimes loads bad rows that break reports. How would you make the import safer?

Load the file into a staging table first, validate it with SQL checks (types, required fields, valid references, duplicates), and move only valid rows into the real table in one transaction, recording rejected rows with reasons. Constraints on the target table act as the final guard.

Full answer

Pipeline:

  1. Staging: load raw text into staging_orders with permissive TEXT columns, so the load itself never fails halfway.
  2. 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_id values with no matching customer
    • duplicates within the file and against existing rows
  3. Reject: insert failing rows into import_rejects(row_no, reason, raw) and report counts.
  4. Publish: INSERT INTO orders SELECT ... FROM staging_orders WHERE valid inside a transaction; if the reject rate passes a threshold, abort the whole batch instead.
  5. Constraints (NOT NULL, CHECK, foreign keys, unique keys) on orders stop 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