Skip to content
Astera Technology

Why is nine sorted ahead of ten in a quantity export?

Sort validated quantity text numerically without rewriting identities.

Download complete case notes and answer keys ↓

Prepare the report input

The fictional source exports canonical whole quantity text in the inclusive range 0..9223372036854775807: 2,10,9. Text sorting compares the strings, not their quantities. Cast only this declared numeric quantity in ORDER BY, keeping the source text in the result.

Every record and report rule below is original and fictional. Reproduce the setup in a fresh SQLite test database; input previews include every table in this small fixture.

Synthetic input: quantities
idunits_text
A2
B10
C9
Download editable CSV ↓
Complete CREATE and INSERT fixture
CREATE TABLE quantities(id TEXT PRIMARY KEY,units_text TEXT NOT NULL); INSERT INTO quantities VALUES('A','2'),('B','10'),('C','9');

Compare misleading and corrected results

Misleading SELECT: reproduce the defect
SELECT id,units_text FROM quantities ORDER BY units_text DESC,id;
Literal misleading result
idunits_text
C9
A2
B10
Download editable CSV ↓
Corrected SELECT
SELECT id,units_text FROM quantities ORDER BY CAST(units_text AS INTEGER) DESC,id;
Literal corrected result
idunits_text
B10
C9
A2
Download editable CSV ↓

Descending text order is 9,2,10; numeric order is 10,9,2. The sort cast applies only to the declared units_text quantity. Invalid text and quantities above SQLite’s signed integer maximum must be rejected before this query; CAST can clamp overflow rather than preserve its order.

Check a fresh boundary case

Add zero and the two largest permitted quantities, 9223372036854775807 and 9223372036854775806. Their distinct numeric order remains intact; zero sorts last.

Recreate the original setup in another fresh database, then apply the change and corrected query below. For an empty result, the table displays a labelled empty-result marker rather than a data record.

Boundary change and corrected query
INSERT INTO quantities VALUES('D','0'),('E','9223372036854775807'),('F','9223372036854775806');
SELECT id,units_text FROM quantities ORDER BY CAST(units_text AS INTEGER) DESC,id;
Literal boundary result
idunits_text
E9223372036854775807
F9223372036854775806
B10
C9
A2
D0
Download editable CSV ↓

Which record leads the corrected order?

Show the worked answer

In the base fixture B=10 leads C=9 and A=2. After the boundary additions E=9223372036854775807 leads F=9223372036854775806, then B,C,A,D=0.

Related resources