views:

606

answers:

1

I have the following query in oracle that I want to use in hibernate but cannot work out how to use the rownum variable in an inner query. The query is as follows:

select emp.prof_key, emp.prof_display_name
from empinst.emp emp
where emp.prof_key IN (select x.object_key
                   from (select event.object_key as object_key
                         from empinst.eventlog event
                         where event.event_name = 'profiles.created'
                         and event.event_source = 'Profiles'
                         order by event.created desc) x
                   where rownum <= 10)

The only way that I can work out how to do it is to break the query into two parts but I assume there must be a more efficient way to do it in hibernate.

Thanks in advance.

Michael.

+1  A: 

Hi Michael,

your query will not filter the 10 most recent records. It will return 10 random records (Random as in unreliable order) since there is no ORDER BY clause.

I'm not familiar with the limitations of hibernate but as with all limiting tools I'm pretty sure you can work around them with a well-thought view.

For example, this view will contain a rank column you can use to filter the 10 most recent record for any combination of (event_name, event_source) based on an ordering column event_date:

CREATE VIEW eventlog_rank_v AS 
SELECT e.*, 
       row_number() OVER (PARTYTION BY e.event_name, 
                                       e.event_source 
                          ORDER BY e.event_date DESC) event_rank
  FROM empinst.eventlog e;
Vincent Malgrat
Hello, well spotted! The order by was missing from the query (I pulled it out of hibernate and started playing with it in sqldev to fix it up and missed the order by statement. I have edited the original question to show it with the order by.
Michael Ransley
@Michael: your query still needs some fixing: the `ORDER BY` clause is evaluated *after* the `WHERE` clause. Basically your query means SELECT 10 rows **randomly**, then `ORDER BY event.created`. See: http://stackoverflow.com/questions/1735614/how-to-select-n-rows/1735644#1735644 or http://stackoverflow.com/questions/909923/more-elegant-sql/909963#909963 for examples of TOP-N queries
Vincent Malgrat
You are correct. I looked at the query more closely and the links you supplied and it appeared that the query was doing exactly as you described. I have changed it again as I can now see it is generating the correct data.
Michael Ransley