Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add column alias to subquery in select statement?

I am trying to run a query where I am using subqueries in the select statement.
This works:

select   
(select sysdate from dual),   
(select 'municipality' from dual),  
(select count(*) from municipality)  
from dual;  

But the resulting columnnames are ugly and therefore I want to add the column aliases.

I am trying to run the following query:

select   
(select sysdate from dual) as sysdate,   
(select 'municipality' from dual) as tablename,  
(select count(*) from municipality) as count  
from dual;

This fails with the ORA 00923: From keyword not found where expected error. Somehow, I am missing something.

Any suggestions?

Thanks.

like image 772
Freeze Avatar asked Oct 21 '22 17:10

Freeze


2 Answers

try wrapping it with double quotes,

select
   (select sysdate from dual) as "sysdate",
   (select 'municipality' from dual) as "tablename",
   (select count(*) from municipality) as "count"
from dual;

SysDate is a reserved keyword. Although, COUNT is an aggregate function but it is permitted to be used.

  • Oracle Reserved Keywords
like image 94
John Woo Avatar answered Oct 31 '22 21:10

John Woo


The only error you had in your code was using keywords sysdate and count as aliases, which is no-no... Using AS is optional also. This works as intended:

select   
 (select sysdate from dual)  s_date,            -- NOT sysdate
 (select 'municipality' from dual)  tablename,  
 (select count(*) from dual) as cnt             -- NOT count
 from dual;

It is OK to use count but in real world it is not advisable and pro-s would not use keywords.

like image 34
Art Avatar answered Oct 31 '22 22:10

Art