Skip to content
Advertisement

Oracle: transpose table

I’ve got the following query

SELECT 1, 2 FROM DUAL

AND I’d like something like

SELECT TRANSPOSE(SELECT 1, 2 FROM DUAL)

Which outputs the same as

SELECT 1 FROM DUAL
UNION
SELECT 2 FROM DUAL

I’d like it to swap lines with columns.

Advertisement

Answer

Using dbms_xmlgen.getxmltype and XMLTABLE:

SELECT *
FROM XMLTABLE('/ROWSET/ROW/*' passing  dbms_xmlgen.getxmltype('SELECT 1, 2, 3 FROM DUAL') 
              COLUMNS val VARCHAR(100) PATH '.');

db<>fiddle demo

Advantage over unpivot – there is no need to specify column list in advance

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement