query optimization for max function in oracle

2.9k views Asked by At

I am having a table name x which contain week-no where datatype of week number is varchar2 which fetches max(week-no) in 22 second. I need to fetch row with max week-no I tried this below query:

select max(to_number(week-no))
from x;

please help and suggest the query which can take less time.

1

There are 1 answers

0
Gordon Linoff On

First, create a functional index:

create index x_weekno_num on x(to_number(week_no));

I think Oracle should be smart enough to use the index for your query. If not, you can try:

select week_no_num
from (select to_number(week_no) as week_no_num
      from x
      order by to_number(week_no) desc
     ) x
where rownum = 1;

I should also point out that if you are storing the number as a character string, then you should pad it with zeros (so "01", "02" and so on). In that case, you can just use max(week_no) and an index directly on the column.