How can I display column names in the result of queries? - oracle

I'm trying to display the name of columns on the top of my file instead of getting only the data I wanna also get the name of the columns
I'm using ORACLE 12C

What you described sounds as if you turned headings off in SQL*Plus. Something like this: by default, headings are visible:
SQL> select * from dept where deptno = 10;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
If you turn them off:
SQL> set heading off
SQL>
SQL> select * from dept where deptno = 10;
10 ACCOUNTING NEW YORK

While display logic should usually be handled in the application, there are workarounds to accomplish something similar with SQL. The below statement uses a few tricks to create an initial row of column names:
select name, age, nationality, city
from
(
select 1 header_1_data_2, 'Name' name, 'Age' age, 'Nationality' nationality, 'City' city
from dual
union all
select 2 header_1_data_2, name, to_char(age), nationality, city
from student
)
order by header_1_data_2;

Related

How to run command "describe table_name" via jdbc to query Oracle database

I know how to run normal select query.
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#xxx";
String uname = "";
String passwd = "";
Connection conn = DriverManager.getConnection(url, uname, passwd);
Statement stmt = conn.createStatement();
String sql = "select * from table_name";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println();
}
But how to run query like sql = "describe table_name" ?
describe is a SQL*Plus command; although it works elsewhere (such as in SQL Developer or TOAD), it is not a "standard" command so I don't think you can use it the way you wanted.
Therefore, as you already know how to run a "normal" query, do it again, but this time by fetching data from user_tab_columns which contains data you need. For example:
SQL> SELECT column_name, data_type, data_precision, data_length, nullable
2 from user_tab_columns
3 where table_name = 'TEMP';
COLUMN_NAME DATA_TYPE DATA_PRECISION DATA_LENGTH N
--------------- --------------- -------------- ----------- -
ID NUMBER 22 Y
ENAME VARCHAR2 10 Y
JOB VARCHAR2 15 Y
DEPT NUMBER 22 Y
HIREDATE DATE 7 Y
LOC VARCHAR2 10 Y
6 rows selected.
which can be compared to
SQL> describe temp
Name Null? Type
----------------------------------------- -------- ----------------------------
ID NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(15)
DEPT NUMBER
HIREDATE DATE
LOC VARCHAR2(10)
SQL>
As of comments: there's that nice view named dictionary you can query and find some useful information, i.e. a system view which then lets you find another information. Here's how:
SQL> select * from dictionary
2 where lower(table_name) like '%user%' and lower(comments) like '%comment%';
TABLE_NAME COMMENTS
------------------------- --------------------------------------------------
USER_COL_COMMENTS Comments on columns of user's tables and views
USER_INDEXTYPE_COMMENTS Comments for user-defined indextypes
USER_MVIEW_COMMENTS Comments on materialized views owned by the user
USER_OPERATOR_COMMENTS Comments for user-defined operators
USER_TAB_COMMENTS Comments on the tables and views owned by the user
OK; it is user_tab_comments and user_col_comments I need. So let's add some comments to the temp table:
SQL> comment on table temp is 'Sample table for Stack Overflow';
Comment created.
SQL> comment on column temp.ename is 'Employee''s name';
Comment created.
Result:
SQL> select * from user_tab_comments where table_name = 'TEMP';
TABLE_NAME TABLE_TYPE COMMENTS
------------------------- ----------- --------------------------------------------------
TEMP TABLE Sample table for Stack Overflow
SQL> select * from user_col_comments where table_name = 'TEMP';
TABLE_NAME COLUMN_NAME COMMENTS
------------------------- --------------- --------------------------------------------------
TEMP ID
TEMP ENAME Employee's name
TEMP JOB
TEMP DEPT
TEMP HIREDATE
TEMP LOC
6 rows selected.
SQL>

Creating temporary table without knowing the columns in oracle

How to create a temporary table in oracle without knowing the number and name of columns.
For example:
Select columnA,columnB,* into temp_table from tableA.
Here,tableA maynot be a simple tablename but maybe derived from many queries.
How can this be achieved?Is there any alternative to this?
In Oracle, you have to first create a table, then insert into it. Or, create it directly (as in my example).
Note that I've created a "normal" table; if it were temporary, you could have chosen between a global or private (depending on database version you use).
For this discussion, I guess that it is just fine:
SQL> create table temp_table as
2 select a.*
3 from (select d.deptno, d.dname, e.ename --> this SELECT is your "tableA"
4 from emp e join dept d
5 on e.deptno = d.deptno
6 where job = 'CLERK'
7 ) a;
Table created.
SQL> select * from temp_table;
DEPTNO DNAME ENAME
---------- -------------------- ----------
10 ACCOUNTING MILLER
20 RESEARCH SMITH
20 RESEARCH ADAMS
30 SALES JAMES
SQL>
Alternatively, create a view and work with it:
SQL> create or replace view v_temp as
2 select d.deptno, d.dname, e.ename
3 from emp e join dept d
4 on e.deptno = d.deptno
5 where job = 'CLERK'
6 ;
View created.
SQL> select * from v_temp;
DEPTNO DNAME ENAME
---------- -------------------- ----------
10 ACCOUNTING MILLER
20 RESEARCH SMITH
20 RESEARCH ADAMS
30 SALES JAMES
SQL>
This statement creates temp_table which contains all columns and data from tableA and two other empty columns, varchar and numeric.
create table temp_table as
select cast (null as varchar2(10)) columnA,
cast (null as number(6)) columnB,
tableA.*
from tableA
If you need only structure, no data, then add:
where 1 = 0
I am not sure why you want to have a temp table as you do not know columns, but you can think of dynamic SQL to create table depending on columns required during your process and then drop it again. From my point of view I think it is not a good design.
I can suggest to think on using collection with 'x' number of columns with datatype as VARCHAR2. During transaction you can populate and process according to you need and it will also remain for that session.

Value Set in Oracle Apps using Union

I need to create a value set which selects items from a custom table for certain run no and union it with Select 'ALL' from dual so that when the user selects ALL the program runs for all the items.
I tried creating a view of the custom table and then used
select item from xx_cust_view where run_no=:$FLEX$.RUN_NO_VS union select 'ALL' from dual
It is saved without error in value set but gives an error when I try to pass values while running the program.
Please suggest.
I don't know Oracle Apps. but I thought that the following example might give you an idea.
It is ran in SQL*Plus, based on HR's departments table. Parameter PAR_DNAME accepts either real department name (such as "Purchasing") or ALL (which is then supposed to return all departments). ROWNUM is here just to restrict number of returned rows (so that I wouldn't display all 27 departments).
Have a look:
SQL> select * from departments
2 where department_name =
3 case when '&&par_dname' = 'ALL' then department_name
4 else '&&par_dname'
5 end
6 --
7 and rownum <= 5;
Enter value for par_dname: Purchasing
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- ------------------------------ ---------- -----------
30 Purchasing 114 1700
SQL> undefine par_dname
SQL> /
Enter value for par_dname: ALL
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
------------- ------------------------------ ---------- -----------
10 Administration 200 1700
20 Marketing 201 1800
30 Purchasing 114 1700
40 Human Resources 203 2400
50 Shipping 121 1500
SQL>
Value set does not allow union, group by .
So i created a view of the union query and used this view in the value set to fetch the values.

Swap these two columns without using update in Oracle sql?

Ename sex
ABC male
Def female
Swap between male & female.
Output should be
Male ABC
Female DEF
Thanks in advance!
Preparing for Interview.
I'm going to assume you have a table defined like:
CREATE TABLE EMP
(ENAME VARCHAR2(20),
SEX VARCHAR2(6));
and that you have the following rows in it:
ENAME SEX
ABC male
Def female
I'll further assume that the output in your question was the result of executing
SELECT * FROM EMP
Now, to answer your question - to get SEX first, then ENAME, try the following:
SELECT SEX, ENAME FROM EMP
If you're trying to concatenate the values of SEX and ENAME so you get back a single column try
SELECT SEX || ' ' || ENAME AS SEX_AND_NAME FROM EMP
Share and enjoy.
The answer is as below: Assuming table name is EMP
UPDATE TABLE EMP
SET ENAME = SEX,
SEX = ENAME;
This will swap the values of the columns ename and sex not the column position.

the number of same record until this row

Is it possible to retrieve current number of same record for each row by using oracle pl/sql?
For example,
I have class table which consists of id, name, age columns
I want to have the sequence of student with the same name and age entering the class, assuming that id is countering up without altering data structure.
Thanks.
Regards,
Jim
Not sure I entirely get what you're asking for; you have an odd turn of phrase. An example of input data and expected result is always useful.
Perhaps something like this:
select id, name, age
from your_table
where (name, age) in
( select name. age
from your_table
group by name, age
having count(id) > 1 )
order by name, age, id
/
You could solve this with analytics. However, you still need an outer query to filter out the records which aren't duplicated, so I'm not sure what you'd gain:
select * from (
select id, name, age
, count(id) over (partition by name, age) as dup_count
from your_table )
where dup_count > 1
order by name, age, id
/
I'm not sure either, but it sounds to me something related to analytic functions. Take this as an example, look at srlno column, calculated using analytic functions:
SELECT empno, deptno, hiredate,
ROW_NUMBER( ) OVER (PARTITION BY
deptno ORDER BY hiredate
NULLS LAST) SRLNO
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, SRLNO;
EMPNO DEPTNO HIREDATE SRLNO
------ ------- --------- ----------
7782 10 09-JUN-81 1
7839 10 17-NOV-81 2
7934 10 23-JAN-82 3
7369 20 17-DEC-80 1
7566 20 02-APR-81 2
7902 20 03-DEC-81 3
7788 20 09-DEC-82 4
7876 20 12-JAN-83 5
More on analyltic functions:
http://www.orafaq.com/node/55
Remember, is a better approach if you can achieve your goal with a SQL instead of PL/SQL.

Resources