Zum Inhalt springen

Lektion 25 · Projects and Reference

Project: Repair a Sales Export in SQL

Practice SQL data cleaning on a messy sales export: stage raw text, validate and convert values, map regions, remove reloads, quarantine failures and reconcile.

In this second project, a fictional sales system exports data that was partly loaded twice. Your job is to produce a trustworthy table of order lines using only SQL. All the data is invented.

The brief

  • Keep one row per order line, identified by order_id and line_no.
  • Reloaded rows share the key. Keep the row from the latest load.
  • qty must be a positive whole number.
  • price_cents is the unit price in cents, as whole-number text.
  • Region values must be mapped.
  • Dates must be real dates in YYYY-MM-DD form.
  • Rejected rows go to a report with a reason.

Step 1: look at the raw data

SQL Profile the raw export

Press Run (or Ctrl + Enter) to see the result here.

There are more rows than distinct lines, so reloads exist. For line 2 of order S1, the quantity changed from 1 to 4 between loads. The latest-load rule decides it.

Step 2: the plan

flowchart LR
  A["raw_sales"] --> B["Latest per key"]
  B --> C["Checks"]
  C --> D["clean_sales"]
  C --> E["Rejects"]

Choose the latest version first, then judge it.

The order matters. If you removed bad rows first and then picked the latest, a broken newest version would let an older one win silently. Here the newest version is judged, and if it fails, it is rejected for review.

Step 3: the full solution

SQLite's date() function returns NULL for text it cannot read. It may also accept some impossible days, such as 30 February, and roll them into the next month. Asking for date(sold_on, '+0 days') and comparing it with the original text catches both cases.

SQL Clean, reject and reconcile

Press Run (or Ctrl + Enter) to see the result here.

Reconcile

In the third result, raw_rows should equal superseded + rejected + clean_rows. Add the numbers and check.

The revenue query is only as complete as the clean table. Rejected rows are not included, so say that next to the totals. In real work, compare with a control total from the source and explain the difference line by line.

Note that CASE returns only the first failing reason. To list all reasons, build a report with UNION ALL, as in the SQL validation lesson. This project also assumes that order_id and line_no are clean and that one load never repeats a key with different values. A real export needs checks for those too.

Extend it

  1. Add rules for an empty order_id or a non-numeric line_no.
  2. Reject dates after a fixed report date.
  3. Report lines whose values changed between loads.
  4. After the owner confirms that Nrth means North, add it to the mapping and run everything again.
  5. Rebuild the solution in pandas and compare the totals.

Common mistake: adding Nrth to the mapping on your own because it "obviously" means North. It is likely, but the data owner should confirm it.

How the solution works

Read the script from top to bottom as a chain of small decisions. The latest view answers "which version of each line counts?". It numbers the rows for each key from the newest load to the oldest and keeps the first. The judged view answers "is that version acceptable, and if not, why?". A NULL reason means that the row passed. Only then does the script convert text to numbers and insert rows into the typed table.

The LEFT JOIN to the region map matters. With an inner join, the row with Nrth would vanish from both the clean table and the reject report, and your reconciliation would no longer add up. Keeping it with an empty region lets the rule catch it.

The order of the CASE branches decides which reason a row reports when it has several problems. The quantity pattern runs before the positive check, so -1 is reported as "not a whole number" because of its minus sign. If users need a clearer message for negative values, add a separate branch before the general one.

The final table has its own CHECK, NOT NULL and key constraints. They repeat some of the rules on purpose. If a later edit to the view lets a bad quantity through, the insert fails loudly instead of storing it.

Present the result

A useful handover has three parts: the clean table, the reject report with the original values and a short note. The note says how many rows arrived, how many older versions were replaced, how many were rejected for each reason and which questions are open, such as the meaning of Nrth. Tell the reader that revenue will change if rejected rows are repaired and loaded later.

Questions for the owner

Finish the project by listing what you still need to know. Is a negative quantity a return that belongs in a separate table? What was the real date of the order dated 30 February? Is Nrth a typing mistake for North? Can a newer load delete a line, and if so, how would the export show it?

The last question is important. This solution keeps lines that appear only in older loads. That is right if each load adds or corrects lines, and wrong if each load replaces the whole file.

Test your changes

Each time you add a rule, add one raw row that breaks it and confirm that the row appears in the reject report with the expected reason. Then confirm that the reconciliation numbers still add up.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Why choose the latest version before validating?

    Filtering bad rows first would let stale data take their place without anyone noticing.
  2. 2. How should rejected rows appear in a revenue report?

    Readers need to know that the total does not include rejected records.
  3. 3. What is reconciliation?

    It shows whether any records vanished or appeared without explanation.

Summary

  • Stage raw text and judge the latest version of each key.
  • Validate before casting and map categories with a table.
  • Record rejection reasons and enforce rules on the clean table.
  • Reconcile row counts and totals before you trust results.

Next: Data Cleaning Glossary and Cheat Sheet

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.