22. The invoice numbers that sort like words

SQLEasySchema trap

data types · casting · string comparison · joins

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Invoice numbers are plain running numbers: a higher number means a later invoice. In the invoices table they are stored as text, because the old billing system printed them with leading zeros (0042). The payments table, built later, stores the same numbers as integers.

A customer statement shows the customer's latest invoice. One customer complained that their statement stops at invoice 99, although they have received invoice 1000.

Input tables

invoices

One row per invoice.

Column Type Description
invoice_no STRING The invoice number as text. Older invoices are padded with zeros to four digits (0042); newer ones are not (105, 1003).
customer_id BIGINT The customer who was invoiced.
amount DECIMAL(10,2) Invoice value in rupees.

payments

One row per paid invoice. An invoice is paid at most once.

Column Type Description
invoice_no BIGINT The number of the invoice that was paid.
paid_on DATE Date of the payment.

Requirement

Return one row per customer.

  • invoice_count is the number of invoices of the customer.
  • latest_invoice_no is the customer's highest invoice number, compared as a number. 1000 is later than 99, and 0042 is invoice 42.
  • paid_invoices is how many of the customer's invoices have a payment. Invoice 0042 is paid if payments has a row for 42.

Expected output

One row per customer.

Column Type Description
customer_id BIGINT
invoice_count BIGINT
latest_invoice_no BIGINT The highest invoice number, as a number.
paid_invoices BIGINT 0 if none are paid.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

A column's type decides how its values are compared. invoice_no holds numbers, but it is a STRING, so it is compared the way words are: character by character, from the left.

  • '99' > '1000' is true. The first characters are 9 and 1, and 9 is later. Nothing after that is looked at.
  • '0042' = '42' is false. They are different strings.

So the fix is one cast, done once, and used for everything:

CAST(i.invoice_no AS BIGINT)

MAX of that is the latest invoice, and joining on it finds invoice 42 in payments whether the text says 0042 or 42.

COUNT(p.invoice_no) counts the invoices that found a payment. The join has to be a LEFT JOIN, or unpaid invoices disappear and take invoice_count down with them.

There are 176 invoices for 25 customers; 60 of them are zero-padded. 119 have a payment.

Common wrong answers

MAX(invoice_no) on the text. Returns the "largest" string. Customer 25 has invoices 0009, 99, 100 and 1000, and the text maximum is 99. That is the statement that stops too early. Wrapping the result in a cast, CAST(MAX(invoice_no) AS BIGINT), does not help: the wrong value has already been picked. On this data the latest invoice is wrong for 22 of the 25 customers.

Cast first, then aggregate.

Leaving latest_invoice_no as text. Even where the value is right, the column is a STRING and the check reports the type. The output column is BIGINT.

Joining on text: CAST(p.invoice_no AS STRING) = i.invoice_no. Turns 42 into '42', which is not '0042'. Every payment for a padded invoice is lost: only 82 of the 119 payments still match, and paid_invoices is too low for 19 customers. No error, no warning.

Padding the number: LPAD(CAST(p.invoice_no AS STRING), 4, '0') = i.invoice_no. Fixes 0042 and breaks 105, which becomes 0105 and no longer matches. The padding rule changed halfway through the data, so no single text format fits. Wrong for 22 customers.

INNER JOIN to payments. Keeps only paid invoices, so invoice_count and latest_invoice_no are computed from those alone. Wrong for 23 customers.

What Spark does if you join without any cast

LEFT JOIN payments p ON p.invoice_no = i.invoice_no

This compares a BIGINT with a STRING, and it returns the right answer. Spark does not compare them as text: the query plan shows it casting the string side, cast(invoice_no as bigint). DuckDB does the same.

It works, but you are relying on a rule you did not write. In Spark 4 the same implicit cast fails the whole query the day one invoice number is not a number (INV-17). Write the cast yourself, so the intent is visible; if dirty values are possible, use TRY_CAST and decide what a NULL means.

The real fix

Store numbers as numbers. A text key that is "really a number" will be compared as text by someone, in some query, sooner or later. If the leading zeros matter for display, format them at display time.

Edge cases in the data

Case Where What it catches
Zero-padded numbers invoices 1 to 60 Joining on text.
Unpadded numbers of three and four digits 61 to 140, 1000 to 1035 MAX on text; LPAD to four.
One invoice of every length customer 25: 0009, 99, 100, 1000 Text MAX returns 99.
Only padded invoices customer 24 Text MAX happens to be right here, which is why the bug survives spot checks.
Unpaid invoices 57 invoices INNER JOIN.