Question

Hello all :) I have this query in Oracle 10g:

SELECT 
  LAST_VALUE(SERIAL_ID) OVER (),
  LAST_VALUE(COLOR) OVER ()
FROM (
  SELECT SERIAL_ID, COLOR FROM TABLE_1
  UNION ALL
  SELECT SERIAL_ID, COLOR FROM TABLE_2
) WHERE SERIAL_ID = <PUT UNIQUE ID TO TABLE_1 and TABLE_2 HERE>

TABLE_1 and TABLE_2 have the exact same schema, but different data. There is a unique constraint on SERIAL_ID, but one SERIAL_ID can be found in both tables.

So far the LAST_VALUE(COLOR) OVER () has always returned the value from TABLE_2 over TABLE_1 when there is a match in TABLE_2. Which is what I want.

I cannot find information in the documentation that tells me that the order from UNION ALL will get preserved. In my opinion UNION ALL is from the set realm, and I don't know if Oracle reserves the right to present this set in undefined order.

I want to make sure that the order will stay the same.

Best regards

Was it helpful?

Solution

Unless it's documented it isn't safe to assume anything about ordering, other than Tom Kyte's mantra. Even it appears to always work now, that doesn't mean you won't find it working differently one day, in the current or a future version.

You could ensure this by adding a flag to each branch of the union:

SELECT 
  LAST_VALUE(SERIAL_ID) OVER (ORDER BY FLAG
    RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
  LAST_VALUE(COLOR) OVER (ORDER BY FLAG
    RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM (
  SELECT SERIAL_ID, COLOR, 1 AS FLAG FROM TABLE_1
  UNION ALL
  SELECT SERIAL_ID, COLOR, 2 AS FLAG FROM TABLE_2
) WHERE SERIAL_ID = <PUT UNIQUE ID TO TABLE_1 and TABLE_2 HERE>

This will work even if you (artifically) break it by adding an ORDER BY FLAG DESC to the inner query - SQL Fiddle showing that in action.

OTHER TIPS

Well, UNION ALL always returned ordered data for me. Order is by all columns, starting from first one. To set records in order you need, you will have to generate some additional field in both internal queries and then order on that field in outer query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top