Some columns nulled when using rownum with data from an inner select
772653May 12 2010 — edited Sep 23 2010Hello,
In one of the complex queries generated by my application, some of the columns return null values when there are some actual values. While the complex query is generated by Hibernate, the problem can be reproduced by using SQL directly. It seems that this is partly due to rownum.
Here is an example query that fails:
select row_.*, rownum from (select this_.ID, this_.COL_A, this_.COL_B, this_.COL_C from MY_TABLE this_ where this_.ID in (select this_.ID as y0_ from MY_TABLE this_) order by this_.COL_B asc ) row_
h2. Sample data
This can be applied to the following example table/data:
CREATE TABLE "MY_TABLE"
( "ID" VARCHAR2(20) PRIMARY KEY NOT NULL,
"COL_A" VARCHAR2(20),
"COL_B" VARCHAR2(20),
"COL_C" VARCHAR2(20)
) ;
Insert into MY_TABLE (ID,COL_A,COL_B,COL_C) values ('ID1','QWE','WER','ERT');
Insert into MY_TABLE (ID,COL_A,COL_B,COL_C) values ('ID2','ASD','SDF','DFG');
Insert into MY_TABLE (ID,COL_A,COL_B,COL_C) values ('ID3','ZXC','XCV','CVB');
h2. Query without rownum
select row_.* from (select this_.ID, this_.COL_A, this_.COL_B, this_.COL_C from MY_TABLE this_ where this_.ID in (select this_.ID as y0_ from MY_TABLE this_) order by this_.COL_B asc ) row_
This query produces the following results:
ID, COL_A, COL_B, COL_C, ROWNUM
ID2, ASD, SDF, DFG
ID1, QWE, WER, ERT
ID3, ZXC, XCV, CVB
h2. Query with rownum
select row_.*, rownum from (select this_.ID, this_.COL_A, this_.COL_B, this_.COL_C from MY_TABLE this_ where this_.ID in (select this_.ID as y0_ from MY_TABLE this_) order by this_.COL_B asc ) row_
This query produces the following results:
ID, COL_A, COL_B, COL_C, ROWNUM
ID2, (null), SDF, (null), 1
ID1, (null), WER, (null), 2
ID3, (null), XCV, (null), 3
h2. Other variants
Removing the inner "where this_.ID in (select this_.ID as y0_ from MY_TABLE this_)", which is completely unnecessary indeed seems to produce the right results.
However, I'd like to know if there's something wrong (unnecessary complexity excluded) with this query:
select row_.*, rownum from (select this_.ID, this_.COL_A, this_.COL_B, this_.COL_C from MY_TABLE this_ where this_.ID in (select this_.ID as y0_ from MY_TABLE this_) order by this_.COL_B asc ) row_
Does anyone know why COL_A and COL_C are not populated (and why is it just the column with the ORDER BY)?
I do realise the Hibernate framework (which is used by my application) does things in a convoluted way here, but unless there's something wrong which I can't spot here, this seems to be a legitimate query and should still produce the right results.
(I'm using Oracle 11g R2)
Best wishes,
Bruno.