Using SQLite3, I am attempting to order my results by casting a TEXT string to INTEGER. Here is my query:
SELECT id,section FROM contract_sections ORDER BY CAST (section AS int)
The ‘section’ column is TEXT, and consists of a hierarchical/canonical identifier, i.e. 1.2.1, where each decimal reflects another level of depth within a hierarchy. I want my results returned in order (i.e. 1.2.8, 1.2.9, 1.2.10, etc). If I simply order by the ‘section’ column without a cast, i get a result that looks like:
1.1,
1.10,
1.2,
…
But with the aforementioned query with cast, it seems to be ordering correctly now, as in:
1.1,
1.2,
…
1.9,
1.10
My question is, if I cast this string to an int, what value is SQLite converting it to, and how will it be ordered as a result? It seems to be ordering things as I want at the moment, but want to avert any unforseen bugs.
Different databases handle casts to integers and floats differently.
In the cast of SQL Lite, it converts the initial segment of the string that looks like an integer to an integer. So, cast(‘1.2.1’ as int) results in the integer 1.
It behaves similarly for numerics, so cast(‘1.2.1’ as real) results in the value 1.2.
This behavior is documented here (http://www.sqlite.org/lang_expr.html).
Other databases might return an error in this case.