12

I have the following query in SQLite:

SELECT * FROM t1 ORDER BY t1.field

Where t1.field is a text column containing numbers. Is it posible to force SQLite to consider the values of t1.field as numbers instead of strings (whithout doing ALTER TABLE)? Right now the sort is a pure string one, so 10 goes before 2.

Thank you.

1 Answer 1

27

Well, found a solution:

SELECT * FROM t1 ORDER BY t1.field + 0

The + 0 part seems to force conversion to number

Sign up to request clarification or add additional context in comments.

4 Comments

thank you this helped me, out of interest on what platform were you using SQLite on?
SELECT * FROM t1 ORDER BY CAST(t1.field AS INTEGER)
You can even sort mixed data. If using ORDER BY t1.field + 0, t1.field, this will first sort all numbers, then all strings that could not be converted to a number -> ["no", "yes", "1", "5", "10", 50"]
It will even order mixed strings: ["10 dogs", "2 dogs", "35 dogs"] becomes ["2 dogs", "10 dogs", "35 dogs"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.