Skip to Main Content
  • Questions
  • How to retrieve two columns into rows without using UNION / UNION ALL

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Rajya Lakshmi.

Asked: January 04, 2016 - 7:22 am UTC

Last updated: January 04, 2016 - 11:28 am UTC

Version: 10.2.0

Viewed 10K+ times! This question is

You Asked

I have a table with only two columns of same datatype varchar2.

How can retrieve all the values into a single column without using UNION?

(Select col1 from test union select col2 from test) works but it causes redundancy of the code especially when the two columns are formed by joining many tables.

eg. Select * from test gives

Col1 Col2
-----------
AB CD
EF GH
IJ KL

Expecting as

Col
----
AB
CD
EF
GH
IJ
KL



and Connor said...

I dont really understand the issue with UNION / UNION ALL , but anyway, you can use UNPIVOT

SQL> with t as
  2   ( select 'AB' c1, 'CD' c2 from dual union all
  3     select 'EF' c1, 'GH' c2 from dual )
  4  select x
  5  from t
  6  unpivot ( x for y in ( c1 as 'C1', c2 as 'C2'));

X
--
AB
CD
EF
GH


Footnote: https://connormcdonald.wordpress.com/2016/01/02/new-years-resolutiontest-cases/

Rating

  (3 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Rajya Lakshmi Jampani, January 04, 2016 - 9:22 am UTC

The introduction of "With t as" tag was useful. Colud have been better if an alternative was suggested instead of Unpivot as Pivot/Unpivot is introduced in Oracle 11g.
Connor McDonald
January 04, 2016 - 11:28 am UTC

Ah, apologies for that. In that case, I think you're back to UNION / UNION ALL.

Just Cross join.

Rajeshwaran, Jeyabal, January 04, 2016 - 12:34 pm UTC

rajesh@ORA10G> set feedback off
rajesh@ORA10G> drop table t purge;
rajesh@ORA10G> create table t(x varchar2(5),y varchar2(5));
rajesh@ORA10G> insert into t values('AB','CD');
rajesh@ORA10G> insert into t values('EF','GH');
rajesh@ORA10G> insert into t values('IJ','KL');
rajesh@ORA10G> commit;
rajesh@ORA10G>
rajesh@ORA10G> set feedback on
rajesh@ORA10G> select decode(r,1,x,2,y)
  2  from t, (select level r
  3     from dual
  4     connect by level <=2)
  5  order by t.rowid
  6  /

DECOD
-----
AB
CD
GH
EF
KL
IJ

6 rows selected.

rajesh@ORA10G>

With MODEL Clause in 10g

Rajeshwaran, Jeyabal, January 04, 2016 - 12:38 pm UTC

rajesh@ORA10G> select z
  2  from t
  3  model
  4    partition by (rowid)
  5    dimension by (1 c1)
  6    measures ( cast(null as varchar2(5)) z,x,y)
  7    rules
  8    ( z[0] = x[1] ,
  9      z[1] = y[1] )
 10  order by rowid ,z
 11  /

Z
-----
AB
CD
EF
GH
IJ
KL

6 rows selected.

rajesh@ORA10G>