Full answer
String comparison works like a dictionary. It compares the first character, and only looks at the next one when the first characters tie. '10' starts with '1', which is smaller than '9', so '10' sorts first no matter how long it is.
CREATE TABLE roll_call (roll TEXT, name TEXT);
INSERT INTO roll_call VALUES ('9','Ira'),('10','Jon'),('2','Kim'),('1','Lia');
SELECT roll, name FROM roll_call ORDER BY roll;| roll | name |
|---|---|
| 1 | Lia |
| 10 | Jon |
| 2 | Kim |
| 9 | Ira |
The quick fix is to sort by the numeric value:
SELECT roll, name FROM roll_call ORDER BY CAST(roll AS INTEGER);| roll | name |
|---|---|
| 1 | Lia |
| 2 | Kim |
| 9 | Ira |
| 10 | Jon |
The real fix is to store numbers as numbers. A text column accepts '9', ' 9' and 'nine', and all of them break numeric sorting or casting in different ways. If the value has letters, like 'CS-10', either split it into a prefix and a numeric part, or pad the number to a fixed width ('CS-009', 'CS-010') so text order and numeric order agree.
There is an SQLite detail here. SQLite uses type affinity, so if the column had been declared INTEGER, the text '10' would have been converted to the integer 10 on insert and sorted correctly. Declaring it TEXT keeps it as text.
CREATE TABLE roll_call (roll TEXT, name TEXT);
INSERT INTO roll_call VALUES ('9','Ira'),('10','Jon'),('2','Kim'),('1','Lia');
SELECT roll, name FROM roll_call ORDER BY roll;
SELECT roll, name FROM roll_call ORDER BY CAST(roll AS INTEGER);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Text is compared character by character
- CAST in ORDER BY gives numeric order
- Store numeric values in numeric columns
- Zero-padding makes text order match numeric order
Common mistakes
- Fixing the sort with CAST while leaving bad data types in the schema
- Casting values that contain letters, which gives 0 or an error depending on engine
Follow-ups
- What does CAST('12abc' AS INTEGER) return in SQLite?
- How does type affinity affect this in SQLite?
Tips
- Explain the cause in one line before giving the fix