ROWNUM & ORDER BY

Dear Oracle experts,
I am not getting the expected output when i use ROWNUM & ORDER BY clause in the same query.
Here is issue. Let us say, we have a table TEST with field last_update_date.
CREATE TABLE TEST(LAST_UPDATE_DATE DATE);
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('23-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('22-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('21-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('20-MAY-05'));
INSERT INTO TEST VALUES(TO_DATE('13-JUN-04'));
INSERT INTO TEST VALUES(TO_DATE('30-APR-05'));
INSERT INTO TEST VALUES(TO_DATE('09-MAR-05'));
INSERT INTO TEST VALUES(TO_DATE('12-MAY-05'));
select * from TEST
where trunc(LAST_UPDATE_DATE) >= to_date('09-MAR-05')
and trunc(LAST_UPDATE_DATE) <= to_date('22-MAY-05')
and rownum < 3
order by LAST_UPDATE_DATE;
The above query is supposed to return
09-MAR-05
30-APR-05
But it is returning
21-MAY-05
22-MAY-05
If i remove ROWNUM, then it returns in the correct order. But i want to restrict number of records in the same query.
Anybody can help me on this?.
Regards
Govind

Hello all,
I need yours expertise again.
I created FBI on last_update_date. It works fine.
When i run this query without order by clause, it takes only fraction of second to complete the process. If i add order by caluse, it takes for ever to complete the query. The table has 30 million records.
Anybody can help me on this?.
SELECT *
FROM (SELECT *
FROM TEST
where trunc(LAST_UPDATE_DATE) >= to_date('09-MAR-05')
and trunc(LAST_UPDATE_DATE) <= to_date('22-MAY-05')
order by LAST_UPDATE_DATE)
where rownum < 3
Regards
Govind

Similar Messages

  • TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)

    제품 : SQL*PLUS
    작성날짜 : 2003-07-30
    TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)
    =========================================================
    PURPOSE
    Explanation
    SQL*PLUS에서 ORDERING 순으로 NUMBERING하기를 원하는 경우가 많으나,
    ORDERING이 되기 전에 RANDOM ACCESS 시
    ROWNUM이 ASSIGN되기 때문에, 다음과 같은 결과가 나타날 것이다.
    SQL> select ename, rownum from emp;
    ENAME ROWNUM
    ALLEN 1
    JONES 2
    BLAKE 3
    CLARK 4
    KING 5
    ADAMS 6
    JAMES 7
    FORD 8
    SQL> select ename, rownum from emp order by ename;
    ENAME ROWNUM
    ADAMS 6
    ALLEN 1
    BLAKE 3
    CLARK 4
    FORD 8
    JAMES 7
    JONES 2
    KING 5
    Example
    다음의 몇 가지 방법을 이용하여 ORDERING 순으로 NUMBERING을 나타내어 보자.
    1) RECORD를 COUNT하는 방법 (DATA가 많은 경우 부적절)
    SQL> select A.ename, count(*) position
    2 from emp A, emp B
    3 where A.ename > B.ename
    4 or A.ename = B.ename and A.empno >= B.empno
    5 group by A.empno, A.ename
    6 order by A.ename, A.empno;
    ENAME POSITION
    ADAMS 1
    ALLEN 2
    BLAKE 3
    CLARK 4
    FORD 5
    JAMES 6
    JONES 7
    KING 8
    2) INDEX를 이용하는 방법
    SQL> create index sort_ix on emp (ename);
    Index created.
    SQL> select ename, rownum from emp where ename > ' ';
    ENAME ROWNUM
    ADAMS 1
    ALLEN 2
    BLAKE 3
    CLARK 4
    FORD 5
    JAMES 6
    JONES 7
    KING 8
    cf) descending인 경우 아래처럼 hint 사용 바람
    select /*+ index_desc(emp ename_ix) */
    ename, rownum from emp
    where ename > ' ' and rownum < 4;
    3) OPTIMIZER를 이용하는 방법
    SQL> select rownum, ename
    2 from emp , dual
    3 where emp.ename = dual.dummy (+);
    ROWNUM ENAME
    1 ADAMS
    2 ALLEN
    3 BLAKE
    4 CLARK
    5 FORD
    6 JAMES
    7 JONES
    8 KING
    위에서 언급한 내용에 더해서 rownum을 where 절에 사용함에 있어서는
    rownum 1을 포함하는 range(예 : 'where rownum <= 100')에 대해서만
    정상적인 조회가 가능하다.
    만약 rownum 1을 포함하지 않는 range(예 : 'where rownum between 50 and 100')
    에 대한 자료 조회를 원한다면 다음과 같이 in-line view를 이용하는 방법을
    사용할 수 있다.
    select rn, ename
    from ( select rownum rn, ename
    from emp)
    where rn between 3 and 5 ;
    RN ENAME
    3 BLAKE
    4 CLARK
    5 KING
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 VIEW
    2 1 COUNT
    3 2 TABLE ACCESS (FULL) OF 'EMP'
    * 이 때 in-line view의 rownum에는 반드시 alias를 이용해야 한다.
    in-line view에 의해서 선택되어지는 data가 많다면 performance가
    떨어질 수 있다.
    Reference Documents
    -------------------

    제품 : SQL*PLUS
    작성날짜 : 2003-07-30
    TIPS(46) : ROWNUM(ORDERING 순으로 NUMBERING, RANGE SELECT)
    =========================================================
    PURPOSE
    Explanation
    SQL*PLUS에서 ORDERING 순으로 NUMBERING하기를 원하는 경우가 많으나,
    ORDERING이 되기 전에 RANDOM ACCESS 시
    ROWNUM이 ASSIGN되기 때문에, 다음과 같은 결과가 나타날 것이다.
    SQL> select ename, rownum from emp;
    ENAME ROWNUM
    ALLEN 1
    JONES 2
    BLAKE 3
    CLARK 4
    KING 5
    ADAMS 6
    JAMES 7
    FORD 8
    SQL> select ename, rownum from emp order by ename;
    ENAME ROWNUM
    ADAMS 6
    ALLEN 1
    BLAKE 3
    CLARK 4
    FORD 8
    JAMES 7
    JONES 2
    KING 5
    Example
    다음의 몇 가지 방법을 이용하여 ORDERING 순으로 NUMBERING을 나타내어 보자.
    1) RECORD를 COUNT하는 방법 (DATA가 많은 경우 부적절)
    SQL> select A.ename, count(*) position
    2 from emp A, emp B
    3 where A.ename > B.ename
    4 or A.ename = B.ename and A.empno >= B.empno
    5 group by A.empno, A.ename
    6 order by A.ename, A.empno;
    ENAME POSITION
    ADAMS 1
    ALLEN 2
    BLAKE 3
    CLARK 4
    FORD 5
    JAMES 6
    JONES 7
    KING 8
    2) INDEX를 이용하는 방법
    SQL> create index sort_ix on emp (ename);
    Index created.
    SQL> select ename, rownum from emp where ename > ' ';
    ENAME ROWNUM
    ADAMS 1
    ALLEN 2
    BLAKE 3
    CLARK 4
    FORD 5
    JAMES 6
    JONES 7
    KING 8
    cf) descending인 경우 아래처럼 hint 사용 바람
    select /*+ index_desc(emp ename_ix) */
    ename, rownum from emp
    where ename > ' ' and rownum < 4;
    3) OPTIMIZER를 이용하는 방법
    SQL> select rownum, ename
    2 from emp , dual
    3 where emp.ename = dual.dummy (+);
    ROWNUM ENAME
    1 ADAMS
    2 ALLEN
    3 BLAKE
    4 CLARK
    5 FORD
    6 JAMES
    7 JONES
    8 KING
    위에서 언급한 내용에 더해서 rownum을 where 절에 사용함에 있어서는
    rownum 1을 포함하는 range(예 : 'where rownum <= 100')에 대해서만
    정상적인 조회가 가능하다.
    만약 rownum 1을 포함하지 않는 range(예 : 'where rownum between 50 and 100')
    에 대한 자료 조회를 원한다면 다음과 같이 in-line view를 이용하는 방법을
    사용할 수 있다.
    select rn, ename
    from ( select rownum rn, ename
    from emp)
    where rn between 3 and 5 ;
    RN ENAME
    3 BLAKE
    4 CLARK
    5 KING
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 VIEW
    2 1 COUNT
    3 2 TABLE ACCESS (FULL) OF 'EMP'
    * 이 때 in-line view의 rownum에는 반드시 alias를 이용해야 한다.
    in-line view에 의해서 선택되어지는 data가 많다면 performance가
    떨어질 수 있다.
    Reference Documents
    -------------------

  • ROWNUM, ORDER BY, ORA-00907: missing right parenthesis

    M&ouml;chte man nur die ersten 3 Datenzeilen nach einer Sortierung haben, f&uuml;ttert man den SQL Server leicht und verst&auml;ndlich beispielsweise mit:
    SELECT * FROM (SELECT TOP 3 * FROM History ORDER BY Start DESC) AS query1 ORDER BY Start;
    Oracle, so habe ich festgestellt, kapiert das nicht und m&ouml;chte &uuml;berhaupt alles ganz anders. So habe ich herausbekommen, dass es bei Oracle kein TOP, sondern ein ROWNUM gibt. Erste Versuche scheiterten, weil ROWNUM vor ORDER BY ausgef&uuml;hrt wird, die Sortierung also erst nach ROWNUM erfolgt.
    Aber daf&uuml;r soll es eine L&ouml;sung geben, die auch &uuml;berall in Foren aufgef&uuml;hrt wird. Doch leider funktioniert auch die angebliche L&ouml;sung nicht:
    SELECT * FROM (SELECT * FROM History ORDER BY Start) WHERE ROWNUM &lt;= 3;
    {color:#ff0000}ORA-00907: missing right parenthesis{color}
    Was ist denn nun wieder falsch?

    You can check here ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:00.44
    satyaki>
    satyaki>
    satyaki>with History
      2  as
      3    (
      4      select to_date('14.07.06','DD.MM.YY') START_R, to_date('14.07.06','DD.MM.YY') ENDE, 'HZJ' GT_TYP, 2340 GT_ID, 4 SOLL, 0 ANFANGSIST, 4 ENDEIST, 2 STATUS from dual
      5      union all
      6      select to_date('17.07.06','DD.MM.YY'), to_date('17.07.06','DD.MM.YY'), 'JQA', 1234, 1, 0, 1, 2 from dual
      7      union all
      8      select to_date('17.07.06','DD.MM.YY'), to_date('17.07.06','DD.MM.YY'), 'HZJ', 2340, 1, 0, 1, 2 from dual
      9      union all
    10      select to_date('17.07.06','DD.MM.YY'), to_date('17.07.06','DD.MM.YY'), 'JQA', 1234, 1, 0, 1, 2 from dual
    11      union all
    12      select to_date('17.07.06','DD.MM.YY'), to_date('17.07.06','DD.MM.YY'), 'HZJ', 2340, 1, 0, 1, 2 from dual
    13      union all
    14      select to_date('17.07.06','DD.MM.YY'), to_date('17.07.06','DD.MM.YY'), 'HZJ', 2340, 4, 0, 4, 2 from dual
    15    )
    16  select *
    17  from (
    18          select *
    19          from History
    20          order by START_R desc
    21       )
    22  where rownum <= 3;
    START_R   ENDE      GT_      GT_ID       SOLL ANFANGSIST    ENDEIST     STATUS
    17-JUL-06 17-JUL-06 JQA       1234          1          0          1          2
    17-JUL-06 17-JUL-06 HZJ       2340          1          0          1          2
    17-JUL-06 17-JUL-06 JQA       1234          1          0          1          2
    Elapsed: 00:00:00.99
    satyaki>It is running smooth here.
    Regards.
    Satyaki De.

  • Rownum, Order by, inner-inner query

    I have a query where the current approach to handling rownum and order by's doesn't work and was wondering if anyone knew of a way around this. The basic query is as follows:
    Select *
    From <list of tables> T1
    Where....
    And t1.elig_id =
    (Select elig_id
    From (Select elig_id
    From eligibility T2
    where T1.family_number = T2.family_number
    order by date1 desc, date2 desc)
    Where rownum = 1)
    The problem is the T1.family_number = T2.family_number line. Since the join is in the inner-inner query sql does not recognize T1.family_number. Is there anyway around that?

    It is probably not materializing the sub query for every row in the outer select, but IN can be expensive if the sub-query returns a large number of rows. Another way to phrase the statement which may be faster is:
    SELECT t1.*
    FROM <list of tables> T1,
         (SELECT elig_id
          FROM (SELECT elig_id, ROW_NUMBER() OVER (PARTITION BY family_number
                                               ORDER BY date1 DESC date2 DESC) rn
                FROM eligibility)
          WHERE rn = 1) elig
    Where t1.elig_id = elig.elig_id and
          other_conditionsEssentially, use the sub-query as if it were a table (an in-line view actually), and join to it. This may make Oracle materialize it earlier and avoid the inlist processing.
    HTH
    John

  • Order By clause problem with ENAME and Rownum?

    From Scott/Tiger user I run this query from EMP table.
    select rownum,EMPNO,ENAME,JOB from emp
    order by Ename;
    Output is like this
    ROWNUM EMPNO ENAME JOB
    11      11     ADAMS CLERK
    2      2      ALLEN SALESMAN
    6      6      BLAKE MANAGER
    7      7      CLARK MANAGER
    13      13     FORD ANALYST
    12      12     JAMES CLERK
    4      4      JONES MANAGER
    9      9      KING PRESIDENT
    5      5      MARTIN SALESMAN
    14      14      MILLER CLERK
    8      8      SCOTT ANALYST
    1      1      SMITH CLERK
    10      10      TURNER SALESMAN
    3      3      WARD SALESMAN
    Here Rownum order is disturb, I want it also in Ascending order with ENAME.
    Please send the solution of this problem
    Best Regards,
    Shahzad

    select row_number() over (order by ename) as rn, empno, ename, job from emp
      order by ename;

  • ROWNUM can use with ORDER BY clause?

    Hi
    Following i have two quires in ROWNUM order for example..
    1:query
    select rownum,empno,ename,deptno from emp
    where rownum <= 14;
    result:
    rownum empno ename deptno
    1 7369 SMITH 20
    2 7499 ALLEN 30
    3 7521 WARD 30
    4 7566 JONES 20
    5 7654 MARTIN 30
    6 7698 BLAKE 30
    7 7782 CLARK 10
    8 7788 SCOTT 20
    9 7839 KING 10
    10 7844 TURNER 30
    11 7876 ADAMS 20
    12 7900 JAMES 30
    13 7902 FORD 20
    14 7934 MILLER 10
    2:Query , add ORDER BY clause it will change the sequence of ROWNUM.
    select rownum,empno,ename,deptno from emp
    where rownum <= 14
    order by deptno;
    result:
    rownum empno ename deptno
    7 7782 CLARK 10
    9 7839 KING 10
    14 7934 MILLER 10
    1 7369 SMITH 20
    11 7876 ADAMS 20
    13 7902 FORD 20
    8 7788 SCOTT 20
    and so on......
    but i want these records from 2 to 5...how i can query this through ROWNUM or any sequence because ORDER BY clause change the order of ROWNUM and i could get this result.
    rownum empno ename deptno
    9 7839 KING 10
    14 7934 MILLER 10
    1 7369 SMITH 20
    11 7876 ADAMS 20
    please send me general query which i can apply on any table.
    advance thanks.

    My guess is that you are looking for a pagination solution. If so, here is a thread on Asktom:
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:127412348064
    So, essentially, you ORDER BY first and then write a wrapper to get your the rownum.
    If you do it this way, You will also use the top-n optimization that Oracle uses.
    Rahul.

  • How to display S.no adjacent to employees table help plsss

    In a form in tabular format Emp details are displayed
    Adjacent to the table i want to put a Sno display item showing
    1 for 1st employee
    2 for 2nd employee ......
    I thought i could like create a global variable in a package specification in a program unit and assign it to 1
    Package pack1 is
    v_num number :=1;
    end;
    and then write a PRE_ITEM trigger for a Sno item in the object navigator
    In the trigger
    how to display the value inside v_cnt;
    I tried creating a sequence
    create sequence v_seq;
    but the sequence really wont help me as
    it would keep on incrementing
    so how can i display the value inside the v_cnt in a item
    Is it possible not to use a trigger and still achieve this

    BEDE,
    what will the :system.cursor_record show in a tabular block of 10 rows and what the rownum will sho instead (even if you change the where clause or the ordre by) :
    - the :system.cursor_record will show the number of the fetch.
    1-10 rows : 1
    11-20 rows : 2 etc ...
    - the rownum order by field :
    rownum - field
    1- A
    2- B
    3 - C etc..
    - the rownum order by field desc :
    rownum - field
    1 -C
    2 - B
    3 - A etc..
    - the rownum where clause filed != 'B':
    rownum - field
    1 - A
    2 - C
    3 - D etc..
    So Sqlstar_student, just choose the method regarding your needs.
    Regards
    JeanYves

  • Display(s) trashed -- how to redraw

    Folks:
    Recently I've discovered that I can reliably trash both displays by attempting to use Skype's screen-share. The screen starts displaying artifacts like ghosts of moved or maybe previously displayed windows. In short: trashed. Also the system slows down a lot
    Fix: disconnect second (external) display before, or don't use Skype screen-share. OK, no problem.
    But I've also noticed a similar problem without using Skype Screen share. In the most recent case my system went into the screen saver and it wouldn't come back until I activated Force Quit (with cmd-opt-esc). Relaunching Finder cleared up much of the trash on the display and restored normal operation. I also opened the Display Preferences --> Arangement, swapped the orientation of my two displays, then swapped them back. That fixed MOST of the remaining trash on both displays.
    I have a suspicion this issue is linked to my use of X11 and Gimp, and --long term-- I'll need to track that down.
    In the meantime...
    --Any general suggestions?
    --Anyone see problems like this?
    --Is there a keyboard shortcut that refreshes the display(s)?
    TIA,
    hen3ry

    BEDE,
    what will the :system.cursor_record show in a tabular block of 10 rows and what the rownum will sho instead (even if you change the where clause or the ordre by) :
    - the :system.cursor_record will show the number of the fetch.
    1-10 rows : 1
    11-20 rows : 2 etc ...
    - the rownum order by field :
    rownum - field
    1- A
    2- B
    3 - C etc..
    - the rownum order by field desc :
    rownum - field
    1 -C
    2 - B
    3 - A etc..
    - the rownum where clause filed != 'B':
    rownum - field
    1 - A
    2 - C
    3 - D etc..
    So Sqlstar_student, just choose the method regarding your needs.
    Regards
    JeanYves

  • Using order by and rownum in massive tables

    Hi,
    I need to retreive paginated and ordered data from a big table.
    I know some different tips using rownum or the RANK() function and subqueries, these tips work well for small amount of data, but I need to get the data from a table with 200.000 entries (not under my control), and with all those methods is necessary to order first the data and then select your range, so performance is extremely poor.
    Anybody knows a better solution? it doesn't matter if is plain SQL(better) or PL/SQL.
    Thanks in advance

    but I was looking for something like the LIMIT in MySQL or TOP in msSQL where all the sorting is made internally and it's really fast If the data needs sorting, I do not think Oracle would take any longer to do that than the others mentioned, unless the other DBs mentioned, only sort the rows that are actually being returned.
    As for the LIMIT clause, Oracle already has that clause available when FETCHing from a CURSOR:
    SQL> DECLARE
      2      CURSOR emp_cur IS
      3          SELECT * FROM scott.emp;
      4      TYPE emp_rec_table IS TABLE OF emp_cur%ROWTYPE INDEX BY BINARY_INTEGER;
      5      emp_tbl emp_rec_table;
      6  BEGIN
      7      OPEN emp_cur;
      8      LOOP
      9          emp_tbl.DELETE;
    10          FETCH emp_cur BULK COLLECT
    11              INTO emp_tbl LIMIT 5;
    12          EXIT WHEN emp_tbl.COUNT <= 0;
    13          dbms_output.put_line(emp_tbl.COUNT || ' rows fetched using LIMIT clause.');
    14      END LOOP;
    15      CLOSE emp_cur;
    16  END;
    17  /
    5 rows fetched using LIMIT clause.
    5 rows fetched using LIMIT clause.
    4 rows fetched using LIMIT clause.
    PL/SQL procedure successfully completed.
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.3.0 - Production
    SQL>

  • Order BY with ROWNUM in Select List

    Hi,
    I have query like bellow for Oracle 11g:
    create table em_c (vl_s_ec int,id_em_em int,id_empcre_ecr int, id_em_ec int);
    create table em (id_em_em int)
    Select e.id_em_em
    , NVL(
    (SELECT * FROM(SELECT a.vl_s_ec FROM em_c a WHERE a.id_em_em = ec.id_em_em
    AND a.id_empcre_ecr < ec.id_em_ec order by a.id_em_ec DESC) WHERE ROWNUM <= 1) ,0) AS col2
    FROM em_c ec
    INNER JOIN em e on ec.id_em_em = e.id_em_em
    WHERE 1 = 1;
    But inner subselect doesn't see table "em_c ec" from outer FROM clause. That's why following error occurs:
    SQL Error: ORA-00904: "EC"."ID_EM_EC": invalid identifier
    Please help me to make it work.
    Edited by: user11290901 on Dec 17, 2010 2:11 AM

    Correlation names only go one level deep. It's a bit tough to decipher your query so if you want a better response please post the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem combining select, order by, rownum (top-N) and for update

    Hello,
    i have serious problems with this.
    -- drop table testtable;
    create table testTable (id number(10,0) primary key, usage number(10,10));
    -- delete from testtable;
    insert into testtable values (11, 0.5);
    insert into testtable values (10, 0.3);
    insert into testtable values (12, 0.3);
    insert into testtable values (9, 0.3);
    insert into testtable values (8, 0.9);
    insert into testtable values (3, 0.0);
    insert into testtable values (2, 0.02);
    insert into testtable values (1, 0.05);
    insert into testtable values (7, 0.7);
    insert into testtable values (6, 0.4);
    insert into testtable values (5, 0.2);
    insert into testtable values (4, 0.1);
    select * from testtable;
    -- without FOR UPDATE
    select * from (
    select tt.id id_, tt.*
    from testtable tt
    where tt.usage > 0.1
    order by tt.usage desc, tt.id desc
    where rownum <= 10;
    --> WORKS
    -- without ORDER BY
    select * from (
    select tt.id id_, tt.*
    from testtable tt
    where tt.usage > 0.1
    where rownum <= 10
    for update of id_;
    --> WORKS
    -- without WHERE ROWNUM <= 10
    select * from (
    select tt.id id_, tt.*
    from testtable tt
    where tt.usage > 0.1
    order by tt.usage desc, tt.id desc
    for update of id_;
    --> WORKS
    -- But what i need is this:
    select * from (
    select tt.id id_, tt.*
    from testtable tt
    where tt.usage > 0.1
    order by tt.usage desc, tt.id desc
    where rownum <= 10
    for update;
    --> ORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc., SQL State: 42000, Error Code: 2014
    select * from (
    select tt.id id_, tt.*
    from testtable tt
    where tt.usage > 0.1
    order by tt.usage desc, tt.id desc
    where rownum <= 10
    for update of id_;
    --> ORA-02014: cannot select FOR UPDATE from view with DISTINCT, GROUP BY, etc., SQL State: 42000, Error Code: 2014
    I have tried every single solution i could come up with.
    But nothing worked.
    My latest idea is to include a comment in the query and set up an ON SELECT trigger which evaluates the comment and enforeces the lock.
    But i'm not sure if this is even possible.
    I cannot split the statement into two because i need the lock immediately when the wanted rows are selected.
    One major criteria for the rows is the order by. Without it i get a random set of rows.
    And the rownum <= 10 is also needed because i don't want to lock the whole table but only the few needed rows.
    I tried row_number() over (order by ...) but this is considdered a window/group-function which disallows the for update as well as the order by.
    During these tests i noticed, that when using the row_number()-function the resultset is ordered automatically (without an additional order by clause).
    But this doesn't help anyway.
    I tried using piped functions to wrap the select to apply the rownum manually by cursor skip, but this doesn't work either. First of all i wasn't able to wrap the query the way i imagined and second the lock would be applied to the whole resultset anyway but only the reduced rows would be returned.
    I heared about LOCK-hints from other DBs, is there anything similar here?
    Any other solution??
    btw. it has to be high-performance after all.
    Greetings Finomosec;

    No, not perfect.
    This is the expected result (ordered by usage desc, id desc):
    ID     USAGE
    8     0.9
    7     0.7
    11     0.5
    6     0.4
    12     0.3
    10     0.3
    9     0.3
    5     0.2
    This ist the one produced by your statement:
    ID     USAGE
    5     0.2
    6     0.4
    7     0.7
    8     0.9
    9     0.3
    10     0.3
    11     0.5
    12     0.3
    Use limit 5 in your tests, and you will also notice that the following doesn't work either:
    select * from testtable ww where ww.id in
    select id from
    select tt.id, tt.usage
    from testtable tt
    where tt.usage > 0.1
    where rownum <= 5
    order by usage desc, id desc
    for update;
    It's because the order is not applied to the result.
    But the following modification works (at least principally):
    select * from testtable ww where ww.id in
    select id from
    select tt.id, tt.usage
    from testtable tt
    where tt.usage > 0.1
    order by usage desc, id desc
    where rownum <= 5
    order by usage desc, id desc
    for update;
    Thr problem here is:
    I need to expand the following Statement to the above form by (Java-) Code:
    -- statement-A
    select tt.id, tt.usage
    from testtable tt
    where tt.usage > 0.1
    order by usage desc, id desc;
    The main problem is:
    The order by clause needs to be duplicated.
    The problem here is, to identify it (if present) and NOT any order by in inner selects.
    I am using Hibernate and to implement this i have to modify the OracleDialect to solve this problem. I get the statement-A (see above) and have to apply the limit.
    Isn't there any other solution??
    Greetings Finomosec;

  • Order by, cursor, rownum

    i want to select 10 database entires
    from an 8i database with the selector variable and sort the entries by a date
    column.
    but the problem is that my sql statement
    (see below) selects first the entries
    and then the entries get ordered.
    what i need is first the entries ordered
    and then the select. otherwise it is possible
    that i get on the next page with the next
    10 entries that this entries may be with a date that should be on the prev. page.
    has anyone an idea?
    thx
    SELECT *
    FROM (SELECT col1,
    col2
    FROM table
    WHERE ROWNUM < (selector + 10)
    MINUS
    SELECT col1,
    col2
    FROM table
    WHERE ROWNUM < selector)
    ORDER BY TO_DATE (col2, 'DD.MM.YYYY HH24:MI');

    In Oracle 8i, the general format for this sort of "top-n" analysis is:
    SELECT column1, column2, ROWNUM
    FROM (SELECT column1, column2
    FROM table_name
    ORDER BY top_n_column DESC)
    WHERE ROWNUM <= number_of_rows;
    Applying that to this situation, the query would be something like:
    SELECT col1, col2, ROWNUM
    FROM (SELECT col1, col2
    FROM table
    ORDER BY TO_DATE(col2, 'DD.MM.YYYY HH24:MI') DESC)
    WHERE ROWNUM <= 10;
    When you put the ORDER BY clause in a sub-query as above, the ORDER BY is applied before the numbering of the rows, so the pseudo-column ROWNUM has some meaning and usefulness.
    However, for those of us who are still using versions prior to Oracle 8i, we can't have an ORDER BY clause in a sub-query; It will generate a somewhat confusing error about a missing parenthesis. Therefore, the pseudo-column ROWNUM has no meaning or usefulness. So, prior to Oracle 8i, for "top-n" analysis, the general format is something like this (It will also still work in 8i):
    SELECT outer.column1, outer.column2
    FROM table_name outer
    WHERE number_of_rows >=
    (SELECT COUNT (*) + 1
    FROM table_name inner
    WHERE inner.top_n_column > outer.top_n_column)
    ORDER BY outer.top_n_column DESC;
    Applying that to this situation, the query would be something like:
    SELECT outer.col1, outer.col2
    FROM table outer
    WHERE 10 >=
    (SELECT COUNT (*) + 1
    FROM table inner
    WHERE TO_DATE(inner.col2,'DD.MM.YYYY HH24:MI') > TO_DATE(outer..col2,'DD.MM.YYYY HH24:MI'))
    ORDER BY TO_DATE(outer.col2,'DD.MM.YYYY HH24:MI') DESC;
    A lot of people keep asking for queries to select the first few or last few rows entered in a table, without ordering by a specific column (for what purpose I am not sure). It is a common mistake to attempt to use ROWNUM for this purpose. However, ROWID is assigned an incremental value upon input, not upon ordering or retrieval, like ROWNUM. Therefore, the pseudo-column ROWID can be used as a comparison column for the same sort of "top-n" analysis like this:
    For the first n rows:
    SELECT outer.column1, outer.column2, ROWID
    FROM table_name outer
    WHERE n >=
    (SELECT COUNT (*) + 1
    FROM table_name inner
    WHERE inner.ROWID < outer.ROWID)
    ORDER BY ROWID;
    For the last n rows:
    SELECT outer.column1, outer.column2, ROWID
    FROM table_name outer
    WHERE n >=
    (SELECT COUNT (*) + 1
    FROM table_name inner
    WHERE inner.ROWID > outer.ROWID)
    ORDER BY ROWID DESC;
    If you are only attempting to retrieve one row, with or without a comparison column, then you can use things like MIN, MAX, NOT IN, NOT EXISTS, and set operators to find that one row.
    I have seen a lot of confusion on this topic and I hope this explanation was thorough enough to help clarify it for some.
    null

  • Rownum and order by as parameter

    i want a procedure that will accept the 'from' and 'to' parameter (rownum) for paginaton as well as the order by column also as a parameter( the order by changes based on the parameter) , and my query is using multiple table which doesnt have Unique keys, the pagination is not working poperly at that time..
    please have a look in to the procedure..
    CREATE OR REPLACE Procedure P_pagination
    (cur out sys_refcursor,end1 number,start1 number,ordr number)
    as
    Var_sql varchar2(4000);
    begin
    var_sql := ' Select * '||
              ' From '||
              ' (select rownum rwnum,aa.* from ' ||
              ' (select ti.a,t2.a,t3.a,t4.b from t1,t2,t3,t4 where < all the joins> order by '||ordr||' )aa'||
              ' where rownum <='|| end1 ||') ' ||
              ' where rwnum >='|| start1 ;
    open cur for var_sql;
    end ;
    /

    If you don't specify explicit ORDER BY clause
    Oracle wont guarantee the order of the sort. You specify ORDER BY ID , but
    not ORDER BY ID, <<something>> , so you have unrepeatable results. Your order by ID but don't order inside ID. Look:
    SQL> select *
      2  from
      3  (select a.*, rownum rnum
      4  from
      5  (select id, data
      6  from t
      7  order by id) a
      8  where rownum <= 150
      9  )
    10  where rnum >= 148
    11  /
            ID       DATA       RNUM
             0         34        148
             0         54        149
             0         81        150
    SQL> select *
      2  from
      3  (select a.*, rownum rnum
      4  from
      5  (select id, data
      6  from t
      7  order by id) a
      8  where rownum <= 151
      9  )
    10  where rnum >= 148
    11  /
            ID       DATA       RNUM
             0         28        148
             0         34        149
             0         54        150
             0         81        151
    SQL> select *
      2  from
      3  (select a.*, rownum rnum
      4  from
      5  (select id, data
      6  from t
      7  order by id, rowid) a
      8  where rownum <= 150
      9  )
    10  where rnum >= 148
    11  /
            ID       DATA       RNUM
             0         24        148
             0         21        149
             0         35        150
    SQL> select *
      2  from
      3  (select a.*, rownum rnum
      4  from
      5  (select id, data
      6  from t
      7  order by id, rowid) a
      8  where rownum <= 151
      9  )
    10  where rnum >= 148;
            ID       DATA       RNUM
             0         24        148
             0         21        149
             0         35        150
             0         68        151Rgds.

  • Combination of rownum and order by in where

    Hi friends
    This is the simple query pl. have a look.
    SQL> select distinct sal from emp
    2 order by sal desc;
    SAL
    5000
    3000
    2975
    2850
    2450
    1600
    1500
    1300
    1250
    1100
    950
    SAL
    800
    500
    200
    14 rows selected.
    Now I want to list only top 5 salaries from this with sql statement
    like
    5000
    3000
    2975
    2850
    2450

    This feature is available from oracle's 8.1.5 onwards
    Example with an Inline View
    Suppose we have a table emp which contains empname and sal. then using Inline View we can write sql like this:
    SELECT * FROM (SELECT * FROM emp ORDER BY sal DESC)
    WHERE ROWNUM < 5;
    here u will get the top 4 salaries.if u want to avoid same sal then use distict also.If u want 2nd maxima then put rownum=2;
    I think u r tried with oracle 8.0 or below versions.test with oracle 8i or above.Then u will get the result.
    Best wishes
    SHINOY.V.V.
    KODUNGALLUR,
    THRISSUR
    KERALA
    INDIA
    ( WORKING IN[b] IBM BANGALORE)
    Kerala,Thrissur,Kodungallur)
    IBM Bangalore

  • How to : rownum and order by in select statement

    Say I have a select statement with additional 'order by' clause.
    The result set I want prepended by the rownum column.
    But, and here comes the flaw, I want the rownum for the already ordered result set
    not the unordered.
    An example:
    select firstname, lastname from myTable order by lastname;
    When I add the rownum to the select clause,
    'select rownum, firstname, lastname from myTable order by lastname;'
    I might get something like:
    20 Mike Adams
    13 Nina Bravo
    1 Tom Charlie
    But I want the following result:
    1 Mike Adams
    2 Nina Bravo
    3 Tom Charlie
    I could now
    'Select rownum, lastname, firstname from (select firstname, lastname from myTable order by lastname);
    But I guess there is a better way!?!
    which is the best way to accomplish that?
    Thanks for your advice!

    >
    'Select rownum, lastname, firstname from (select firstname, lastname from myTable order by lastname)
    >
    Well if you ask me there is very little difference between this query and the above query
    select rownum, lastname, firstname from mytable;Because rownum is assigned before the order by. The difference is in your query you are assigning a rownum to an ordered resultset but still there is no guarantee oracle is going to read the data in an ordered fashion. In the second query rownum is assigned to an unordered resultset. Again it is the samething. So if you want to guarantee it then I will go for the following option
    select row_number() over(order by lastname) rn, lastname, firstname from mytable
    order by lastnameAlso check this link.
    http://www.oracle.com/technology/oramag/oracle/07-jan/o17asktom.html
    Regards
    Raj
    Edited by: R.Subramanian on Jan 13, 2009 6:20 AM

Maybe you are looking for

  • How can I sync free-run clips to a timeline by timecode?

    I shoot weddings with multiple cameras.  For shooting a lot of the pre-ceremony and reception footage, I have the ability to jam the cameras so that they have the same free-run timecode.  So, as the day goes on I am recording some shots with CAM A an

  • Reading nested jar files

    How to read and display contents of nested jar files Let the jar format is something like this. Parent.jar             child11.png             child12.xml             child13.jar                         child21.png                         child22.xml

  • Embedded video file

    Hi, I've been given a PDF with a video file embedded in it. Is there anyway I can export the video file out of the PDF? Thanks

  • RAF Delta HR - Accidents (Spain) (Altas y fallecimientos)

    Do do know if it is possible to prepare/download this kind of XML format file from any existing SAP HR program ?? It is possible to execute both standard programs in order to get RATSB and PAT accident remittances XML files althougth, as far as I am

  • Audit users who try to login on the db

    Hi Team, The oracle database version is 11g and the OS is solaris sparc 64 bit. I am trying to find the users who try to login into the db user "FEED" which are unsuccessful , what is happeing is, the user put a wrong password , the account gets lock