Published on InterSystems Developer Community (https://community.intersystems.com)

Home > SQL Query returns sorted Integer ID column as string

Question
Dmitry Maslennikov · Oct 23, 2022

SQL Query returns sorted Integer ID column as string

This is not an issue in ObjectScript, due to its typeless nature. But it's essential for external programming languages that care a bit more about types of variables.

And in any case, it's still reproducible in ObjectScript. I have table

CREATE TABLE some_table (
        id INTEGER NOT NULL, 
        x INTEGER, 
        y INTEGER, 
        z VARCHAR(50), 
        PRIMARY KEY (id)
)

And data

INSERT INTO some_table (id, x, y, z) VALUES (1, 1, 2, 'z1');
INSERT INTO some_table (id, x, y, z) VALUES (2, 2, 3, 'z2');
INSERT INTO some_table (id, x, y, z) VALUES (3, 3, 4, 'z3');
INSERT INTO some_table (id, x, y, z) VALUES (4, 4, 5, 'z4');

Pretty simple.

Let's check and fetch all the data. $ListBuild is more sensitive to the type of variables, so, I use it, to check the result.

USER>set rs= ##class(%SQL.Statement).%ExecDirect(,"SELECT id, x, y, z FROM some_table") 

USER>while rs.%Next() { zwrite $listbuild(rs.id, rs.x, rs.y, rs.z) }
$lb(1,1,2,"z1")
$lb(2,2,3,"z2")
$lb(3,3,4,"z3")
$lb(4,4,5,"z4")

The expected result, the first three columns are INTEGER, and the last one is String. Let's sort it by id

USER>set rs= ##class(%SQL.Statement).%ExecDirect(,"SELECT id, x, y, z FROM some_table ORDER BY id") 

USER>while rs.%Next() { zwrite $listbuild(rs.id, rs.x, rs.y, rs.z) }
$lb("1",1,2,"z1")
$lb("2",2,3,"z2")
$lb("3",3,4,"z3")
$lb("4",4,5,"z4")

And now, the first column, which is id, represented as a String

But, if I would like to sort it by some other field, it works well, and all types are correct

USER>set rs= ##class(%SQL.Statement).%ExecDirect(,"SELECT id, x, y, z FROM some_table ORDER BY x DESC") 

USER>while rs.%Next() { zwrite $listbuild(rs.id, rs.x, rs.y, rs.z) }
$lb(4,4,5,"z4")
$lb(3,3,4,"z3")
$lb(2,2,3,"z2")
$lb(1,1,2,"z1")

Is there any workaround for this behavior? Why it changes the type of the resulting column?

#Key Question #Python #SQL #InterSystems IRIS
Product version: IRIS 2022.1
$ZV: IRIS for UNIX (Ubuntu Server LTS for x86-64 Containers) 2022.2 (Build 345U) Thu Sep 22 2022 18:24:07 EDT

Source URL:https://community.intersystems.com/post/sql-query-returns-sorted-integer-id-column-string