Search code examples
oracle-databaseidentifierora-00904case-when

Oracle newbie error: ORA-00904 Invalid identifier when using "case when"


I'm getting an error in a query. This query is OK and returning data (the selects and rownums are for pagination):

select *
from (select a.*, rownum rnum
from (select id_edition, id_document, name, extension, creation_date, url, 
(select inscription_date from edition_student_d0 where id_edition = 12345 and id_third =     12345) inscription_date
from upd_edition_doc_d0
where id_edition = 1071591
order by creation_date desc) a
where rownum <= 10 )
where rnum >= 1

Now I'm trying to include a "case when" and get the url only in some circumstances, so I make these modifications, including a case block:

select *
from (select a.*, rownum rnum
from (select id_edition, id_document, name, extension, creation_date, 
(select inscription_date from edition_student_d0 where id_edition = 12345 and id_third = 12345) inscription_date,
case
when trunc(inscription_date + 90) <= trunc(sysdate) then null
else url
end url
from upd_edition_doc_d0
where id_edition = 1071591
order by creation_date desc) a
where rownum <= 10 )
where rnum >= 1

Oracle launches this error:

ORA-00904: "INSCRIPTION_DATE": invalid identifier

I suppose that's because I'm asking for inscription_date and using it at the same query level, but I don't know how to deal with this.

Also, how can I make what I'm trying to make? I mean, getting url only under a certain condition.

Anybody can help?

Thank you in advance.


Solution

  • You can't refer an alias in the same level of the query.

    You can replace the subquery...

    select *
    from (select a.*, rownum rnum
      from (select id_edition, id_document, name, extension, creation_date, 
               (select inscription_date from edition_student_d0 where id_edition = 12345 and  id_third = 12345) inscription_date,
               case when trunc((select inscription_date from edition_student_d0 where id_edition = 12345 and  id_third = 12345) + 90) <= trunc(sysdate) then null
                 else url
               end as url
               from upd_edition_doc_d0
               where id_edition = 1071591
               order by creation_date desc) a
       where rownum <= 10 )
    where rnum >= 1
    

    OR move the case one level up.

    select *
    from (select a.*, 
          case when trunc(inscription_date + 90) <= trunc(sysdate) then null
           else url
          end as url,
          rownum rnum
      from (select id_edition, id_document, name, extension, creation_date, 
               (select inscription_date from edition_student_d0 where id_edition = 12345 and  id_third = 12345) inscription_date
               from upd_edition_doc_d0
               where id_edition = 1071591
               order by creation_date desc) a
       where rownum <= 10 )
    where rnum >= 1