There is a way to get all the column names of a query, using dbms_sql.describe_columns2
. But, it has to be done in PL/SQL.
For example,
I want to get the list of all columns of the following SQL:
SELECT emp.empno, emp.ename, dept.deptno
FROM emp
INNER JOIN dept
ON emp.deptno = dept.deptno
The following anonymous block would list down all the column names in the exact order they are in the select list:
SQL> set serveroutput on
SQL> DECLARE
2 l_cursor NUMBER := dbms_sql.open_cursor;
3 l_ignore NUMBER;
4 l_desc dbms_sql.desc_tab2;
5 l_cnt NUMBER;
6 BEGIN
7 dbms_sql.parse( l_cursor, 'SELECT emp.empno, emp.ename, dept.deptno
8 FROM emp
9 INNER JOIN dept
10 ON emp.deptno = dept.deptno', dbms_sql.native );
11 dbms_sql.describe_columns2( l_cursor, l_cnt, l_desc );
12 FOR i IN 1 .. l_cnt
13 LOOP
14 dbms_output.put_line( 'Column ' || i || ' is "' || l_desc(i).col_name || '"' );
15 END LOOP;
16 dbms_sql.close_cursor( l_cursor );
17 END;
18 /
Column 1 is "EMPNO"
Column 2 is "ENAME"
Column 3 is "DEPTNO"
PL/SQL procedure successfully completed.
SQL>
It would also give you the ALIASES for the column names as well:
SQL> DECLARE
2 l_cursor NUMBER := dbms_sql.open_cursor;
3 l_ignore NUMBER;
4 l_desc dbms_sql.desc_tab2;
5 l_cnt NUMBER;
6 BEGIN
7 dbms_sql.parse( l_cursor, 'SELECT emp.empno employee_id, emp.ename employee_name, dept.deptno department_no
8 FROM emp
9 INNER JOIN dept
10 ON emp.deptno = dept.deptno', dbms_sql.native );
11 dbms_sql.describe_columns2( l_cursor, l_cnt, l_desc );
12 FOR i IN 1 .. l_cnt
13 LOOP
14 dbms_output.put_line( 'Column ' || i || ' is "' || l_desc(i).col_name || '"' );
15 END LOOP;
16 dbms_sql.close_cursor( l_cursor );
17 END;
18 /
Column 1 is "EMPLOYEE_ID"
Column 2 is "EMPLOYEE_NAME"
Column 3 is "DEPARTMENT_NO"
PL/SQL procedure successfully completed.
SQL>
Since you are using SELECT *`, you could also list down the column names from [DBA|ALL|USER]_TAB_COLUMNS:
SQL> SELECT column_name FROM user_tab_columns WHERE table_name IN ('EMP','DEPT');
COLUMN_NAME
--------------------------------------------------------------------------------
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
DEPTNO
DNAME
LOC
11 rows selected.
This is only valid since you are using SELECT *, else you need to use the anonymous block as I have shown above.