← Back to SQL, page 1

sql-0014 · Easy fresher

A column stores roll numbers as text. Why does ORDER BY put '10' before '9', and how do you fix it?

Text sorts character by character, so '10' comes before '9' because '1' is smaller than '9'. Cast to a number in the ORDER BY, or better, store numbers in a numeric column. In SQLite, ORDER BY CAST(roll AS INTEGER) gives 1, 2, 9, 10.

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.

sql
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;
rollname
1Lia
10Jon
2Kim
9Ira

The quick fix is to sort by the numeric value:

sql
SELECT roll, name FROM roll_call ORDER BY CAST(roll AS INTEGER);
rollname
1Lia
2Kim
9Ira
10Jon

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.

sql
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