USING ROWNUM

Hi,
I have 4 tables ( 1 parent - 3 child). Reference is the primary key/FK in these tables. Two of the child tables have 1..1 mapping with the parent table and I have created a view called data_view that would have all the essential columns from the parent + 2 child tables.
One of the child table (WORKFLOW) holds a 1.. m relationship with the parent table.
Now I want to move data from the 4 tables to two history
tables . One history table has the structure just similar to the data_view and the other history table has the same set of columns as the workflow table.
I tried to code a logic where by I insert the first 1000 rows into the history tables and then delete the same from the base tables. I placed this in a loop and gave the exit criteria as SQL%NOTFOUND
After inserting the first 1000 rows into the history tables and deleting the same from the base tables, the loops exits during the second iteration with the error, primary key constraint in the history table violated.
Am I missing something. Your comments on this would be appreciated
FUNCTION MOV(p_date DATE)
RETURN NUMBER
AS
BEGIN
LOOP
INSERT INTO HIST (
column_names(SELECT
column_names
FROM
dATA_VIEW
WHERE
TE_DATE <= P_DATE
AND REFERENCE NOT IN (SELECT REFERENCE FROM WORKFLOW WHERE PROCESSING_TYPE IN ('K','E'))
AND ROWNUM < 1000 );
EXIT WHEN SQL%NOTFOUND;
INSERT INTO WORKFLOW_HIST
(column_names)
(SELECT
column_names
FROM WORKFLOW
WHERE REFERENCE IN (SELECT reference FROM DATA_VIEW WHERE TE_DATE <= P_DATE
AND REFERENCE NOT IN (SELECT REFERENCE FROM WORKFLOW WHERE PROCESSING_TYPE IN ('K','E'))
AND ROWNUM < 1000));
DELETE FROM BASE CASCADE
WHERE REFERENCE IN ( SELECT reference FROM DATA_VIEW
WHERE TE_DATE <= P_DATE
AND REFERENCE NOT IN (SELECT REFERENCE FROM WORKFLOW WHERE PROCESSING_TYPE IN ('K','E'))
AND ROWNUM < 1000);
COMMIT;
END LOOP;
RETURN 0;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
ROLLBACK;
RETURN SQLCODE;
END MOV;
thanks

Hi,
The problem is just beacuse of ROWNUM..
SELECT REFERENCE FROM WORKFLOW WHERE PROCESSING_TYPE IN ('K','E'))
AND ROWNUM < 1000 );
Instead try this statement...
SELECT REFERENCE FROM (Select Reference from WORKFLOW WHERE PROCESSING_TYPE IN ('K','E')
Order By Reference)
Where ROWNUM <= 1000;
Sol is if you use "order by" inside a subquery and then use ROWNUM, it should solve your problem.
My suggestion is plz dont rely on ROWNUM on these kind of operations. You can get unexpected results.
You can also use ROWNUMBER() instead of ROWNUM.
Thanks...

Similar Messages

  • Issue with complete refresh on materialized view when using rownum

    Hi all,
    I had an issue with rownum when using complete refresh
    I am using rownum when creating materialized view and it is generation correctly.But the issue was when i am refreshing the same ,rownum was not getting sorted in ascending order.
    anyone had come across this scenario

    rownum is determined as the row is output, so "order by rownum" does literally nothing.
    http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm

  • Select a range of rows to be displayed using ROWNUM

    I am trying to select a range of records to be displayed using Rownum
    It works using MINUS
    SQL> select rownum,department_id,department_name from departments where rownum <= 20
    minus
    select rownum,department_id,department_name from departments where rownum < 11;
    but does not work if a range is specified
    select rownum,department_id,department_name from departments where rownum >= 11 and rownum <= 20;
    What has gone wrong?
    Details of what I have tried are as follows:
    Connect to the sample schema HR
    SQL> connect hr/hr
    SQL> desc departments
    Name Null? Type
    DEPARTMENT_ID NOT NULL NUMBER(4)
    DEPARTMENT_NAME NOT NULL VARCHAR2(30)
    MANAGER_ID NUMBER(6)
    LOCATION_ID NUMBER(4)
    List all records in Departments
    SQL> select rownum,department_id,department_name from departments;
    ROWNUM DEPARTMENT_ID DEPARTMENT_NAME
    1 10 Administration
    2 20 Marketing
    3 30 Purchasing
    4 40 Human Resources
    etc......
    26 260 Recruiting
    27 270 Payroll
    27 rows selected.
    List the first 10 records in DEPARTMENTS
    SQL> select rownum,department_id,department_name from departments where rownum <= 10;
    ROWNUM DEPARTMENT_ID DEPARTMENT_NAME
    1 10 Administration
    2 20 Marketing
    etc.....
    10 100 Finance
    List row number from 11 to 20, but cannot no rows selected. Why?
    SQL> select rownum,department_id,department_name from departments where rownum >= 11 and rownum <= 20;
    no rows selected
    Use of MINUS can retrieve row number from 11 to 20
    SQL> select rownum,department_id,department_name from departments where rownum <= 20
    minus
    select rownum,department_id,department_name from departments where rownum < 11;
    ROWNUM DEPARTMENT_ID DEPARTMENT_NAME
    11 110 Accounting
    12 120 Treasury
    13 130 Corporate Tax
    14 140 Control And Credit
    15 150 Shareholder Services
    16 160 Benefits
    17 170 Manufacturing
    18 180 Construction
    19 190 Contracting
    20 200 Operations
    10 rows selected.

    For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.
    Conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows:
    SELECT * FROM employees
    WHERE ROWNUM > 1;
    You can get the selected records based on the rownum using the inline query....
    SQL> select rownum, empno from emp;
    ROWNUM EMPNO
    1 7369
    2 7499
    3 7521
    4 7566
    5 7654
    6 7698
    7 7782
    8 7788
    9 7839
    10 7844
    11 7876
    ROWNUM EMPNO
    12 7900
    13 7902
    14 7934
    14 rows selected.
    SQL> select * from (select rownum rn, empno from emp) where rn > 2 and rn < 5;
    RN EMPNO
    3 7521
    4 7566

  • Needs  help to retrive the last row in a  select query without using rownum

    Hi ,
    i need to retrive the last row from the select sub query without using rownum.
    is there any other way to retrive the last row other than the below query.
    is that the ROWNUM=1 will always retrive the 1 row of the select query ?
    select from*
    *(select ename from employee where dept_id=5 order by desc) where rownum=1;*
    Please advise.
    thanks for your help advance,
    regards,
    Senthur

    957595 wrote:
    Actually my problem is ithat while selecting the parents hiearchy of the child data using
    CONNECT BY PRIOIR query
    I need the immediate parent of my child data.
    For example my connect BY query returns
    AAA --- ROOT
    BBB --PARENT -2
    CCC --PARENT-1
    DDD IS my input child to the connect by query
    Immediate parent of my child data "DDD" ---> CCC(parent -1)
    i want the data "CCC" from the select query,for that i am taking the last row of the query with rownum.
    I got to hear that using ROWNUM to retrive the data will leads to some problem.It is a like a magic number.I am not sure what the problem will be.
    So confusing with using this rownum in my query.
    Please advice!!!It's not quite clear what you're wanting, but perhaps this may help?
    you can select the PRIOR values to get the parent details if you want...
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, lpad(' ',(level-1)*2,' ')||ename as ename, prior empno as mgr
      2  from emp
      3  connect by mgr = prior empno
      4* start with mgr is null
    SQL> /
         EMPNO ENAME                                 MGR
          7839 KING
          7566   JONES                              7839
          7788     SCOTT                            7566
          7876       ADAMS                          7788
          7902     FORD                             7566
          7369       SMITH                          7902
          7698   BLAKE                              7839
          7499     ALLEN                            7698
          7521     WARD                             7698
          7654     MARTIN                           7698
          7844     TURNER                           7698
          7900     JAMES                            7698
          7782   CLARK                              7839
          7934     MILLER                           7782
    14 rows selected.(ok, not the best of examples as the mgr is already known for a row, but it demonstrates you can select prior data)

  • Using rownum in EJB-QL ..Pagination using CMP 2.1

    Hi ,
    Hope this is the right forum .. rather than JDBC .
    My requirement is to implement Pagination using EJB2.1 on weblogic with Oracle DB. This is for an application which is quite old system and is not ready yet to be migrated to EJB3.0. So we are struck with EJB2.1 at the moment.
    We are using EJB-QL to get Search result and now need to add Pagination logic in it. I can find weblogic.ejb.PreparedQuery.setMaxElements() API to specify the upper limit but what am looking for is a lower limit ..somthing like setFirstRow() ..
    Can it be done using CMP Entity Bean 2.1 .. EJBQL or someother way ?
    I have the sql for pagination but am not sucessful in translating it to EJB-QL
    select * from
    select /*+ FIRST_ROWS(n) */ a.*, ROWNUM rnum from
    (your_query_goes_here) a
    where ROWNUM <=:MAX_ROW_TO_FETCH
    where rnum >= :MIN_ROW_TO_FETCH;
    Thanks in advance ! I hope I get a solution soon ..
    Edited to get some answers !!!
    is it possible to use rownum in EJBQL ? I know rownum is specific to Oracle and my application will stay with Oracle. I get this exception
    "EJB QL compilation encountered error: [EJB:013042]The Identifier 'rownum' is neither a cmp-field nor a cmr-field. Re-examine your query."
    Edited by: user11305835 on Oct 12, 2009 10:48 PM

    Beevin
      Both two are not even validated,
      but with the first one as select max(c.id) from customer as c , in this case it is validated but while deploying it is error as , object must be return
      But when i saw  the ejb2.1 specification we can write this type of queries also ?
      Is it problem with was any thing
    Regards
    Somaraju

  • Issue While executing the Query for Pagination using ROWNUM with like

    Issue While executing the Query for Pagination using ROWNUM with like.
    Database is Oracle11G.
    Oracle Database Table contains 8-9 lakh records
    1) SQL equal (=)
    SELECT /*+ FIRST_ROWS(n) */ ROWNUM RNUM, A.* FROM LINE A
    WHERE A.REFERENCE = 'KMF22600920'
    Execution Time:- 0.00869245 seconds
    Returns 2 resultsets
    2) SQL like (one %)
    SELECT /*+ FIRST_ROWS(n) */ ROWNUM RNUM, A.* FROM LINE A
    WHERE A.REFERENCE = 'KMF22600920%'
    Execution Time:- 0.01094301 seconds
    Returns 2 resultsets
    3) SQL like (two%)
    SELECT /*+ FIRST_ROWS(n) */ ROWNUM RNUM, A.* FROM LINE A
    WHERE A.REFERENCE like '%KMF22600920%'
    Execution Time:- 6.43989658 seconds
    Returns 2 resultsets
    In Pagination, we are using Modified version of SQL Query 3) with ROWNUM as mentioned below :-
    4) SELECT * FROM (
    SELECT /*+ FIRST_ROWS(n) */ ROWNUM RNUM, A.* FROM LINE A
    WHERE REFERENCE like '%KMF22600920%' AND ROWNUM <= 20 ) WHERE RNUM > 0
    Execution Time:- Infinite
    ResultSets:- No as execution time is infinite
    a) Instead of like if we use = in the above query it is returning the 2 resultsets (execution time 0.02699282 seconds)
    b) Instead of two % in the above query, if use one example REFERENCE like 'KMF22600920%' it is returning the 2 resultsets (execution time 0.03313019 seconds)
    Issue:- When using two % in like in the above query i.e. REFERENCE like '%KMF22600920%' AND ROWNUM <= 20 ) , it is going to infinite.
    Could you please let us know what is the issue with two % used in like and rownum
    5) Modified version of Option1 query (move out the RNUM condition AND RNUM <= 20)
    SELECT * FROM (
    SELECT /*+ FIRST_ROWS(n) */ ROWNUM RNUM, A.* FROM LINE A
    WHERE REFERENCE like '%KMF22600920%' ) WHERE RNUM > 0 AND RNUM <= 20
    Execution Time:- 7.41368914 seconds
    Returns 2 resultsets
    Is the above query is best optimized query which should be used for the Pagination or still can improve on this ?

    This would be easier to diagnose if there was an explain plan posted for the 'good' and 'bad' queries. Generally speaking using '%' on both sides precludes the use of any indexes.

  • Restricting number of rows in EJB  QL    using rowNum or rowId

    Hii Javaites
    I am using EJB finder methods to get a a list of records from database.
    Now i want that only particular number of records should be fetched.
    For tht i want 2 use rownum or rowId.
    Can anyone plz tell me can we do tht in EJB QL.
    I m using Weblogic 8

    shouldn't use rownum or rowid to do such a thing.
    %

  • Using ROWNUM in ODI

    hey,
    i want to use ROWNUM in my target table (DAYS) like:
    Field 1(rownum) Field2
    1 Monday
    2 Tuesday
    i create a field in my target table and in the mapping i use ROWNUM but it doesnt work.
    Thanks for ur help
    Mehdi

    Hi,
    I think you want to use a sequence generated number for the first column right?
    In that case : from my understanding to what you have posted -
    Step-1 : Create a Procedure and pass the code under 'Details' tab,before this check the right Technology
    Step-2: Create a Scenario,select Native Sequence --> click the correct Schema and check Development --> the created procedure name shows up --> click OK
    Step-3 : Go to Mapping, open Expression editor for that Particular Column, click the Project Sequences and you will find the created Sequence. drag and drop in the editor
    Now run the interface, you will get the desired result. it will generate the sequence num for that particular column
    Regards,
    M

  • How to use ROWNUM in query

    There are 1000 records in the employee table.I need to display 50 records each time by the order of the employees' names. In order to get the employee records from the 51st to the 100nd in the table, I tried to use ROWNUM.
    However, the following query doesn't do the job:
    select first_name, last_name from employee where rownum < 101 and rownum >49 order by last_name, first_name
    I currently use the following query:
    select * from (
    (select first_name, last_name from employee where rownum < 101 order by last_name, first_name)
    Minus
    (select first_name, last_name from employee where rownum < 50 order by last_name, first_name )
    ) order by 2,1
    The query works but is quite complictated. I would like to know if there a simpler way to do so.
    Thanks in advance.
    Helena

    The generally preferred query is something along the lines of
    SELECT *
      FROM ( SELECT a.*, rownum rn
               FROM (<<your query>>) a
              WHERE rownum <= <<MAX VALUE>>)
    WHERE rn >= <<MIN VALUE>><<your query>> here would be
    SELECT first_name, last_name
      FROM employee
    ORDER BY first_name, last_nameNote that if you wanted to use the MINUS construct, you would generally need to move the rownum clause outside the query that is doing the ORDER BY. The query
    SELECT first_name, last_name
      FROM employee
    WHERE rownum < 101
    ORDER BY first_name, last_namefetches the first 100 rows and then orders them, which is not generally what you want.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Can we use rownum in procedures?

    Hi,
    Can we use rownum in procedures"
    Thanks and regards
    Gowtham Sen.

    here is some examples that might be of help.
    SQL> set serveroutput on;
    SQL> create or replace procedure get_employee(p_empno number) as
      2    cursor c1(pEmpNo number) is
      3     select e.rn, e.empno, e.ename
      4       from (select rownum rn, empno, ename
      5               from emp
      6             order by empno) e
      7      where e.empno = pEmpNo;
      8  begin
      9    for c1_rec in c1(p_empno) loop
    10      dbms_output.put_line('The rownum is '||to_char(c1_rec.rn));
    11      dbms_output.put_line('The employee name is '||c1_rec.ename);
    12    end loop;
    13  end;
    14  /
    Procedure created.
    SQL> execute get_employee(7788);
    The rownum is 8
    The employee name is SCOTT
    PL/SQL procedure successfully completed.
    SQL> execute get_employee(7654);
    The rownum is 5
    The employee name is MARTIN
    PL/SQL procedure successfully completed.
    SQL>

  • Java.sql.SQLException: Invalid column index Query: while using ROWNUM

    hi ,
    i am getting the invalid column index query error while executing following query .i m able to run it properly without using rownum but when i append rownum i m getting error.i m using apache queryrunner for execution of query.
    java.sql.SQLException: Invalid column index Query: select * from (
    SELECT
    TO_CHAR(A.REQ_FOR_RATING_ID) RFQID,
    TO_CHAR(F.COV_PLAN_ID) COVPLANID,
    B.FIRM_NAME FIRMNAME,
    B.PRIMARY_ZIP_CD ZIP,
    A.PRODUCR_CD PRODUCERCD,
    A.PRODUCR_NAME PRODUCER,
    H.COV_NAME COVDESP,
    C.SALE_OFFC_CD SALEOFFCCD,
    C.USR_OFFC_NAME USROFFC,
    C.USR_NAME USR,
    C.USR_REP_CD USRREPCD,
    to_char((SELECT TO_CHAR(COUNT(EMP_NBR)) COUNT FROM ROSTR_DATA WHERE ROSTR_ID = F.ROSTR_ID)) AS count,
    TO_CHAR(B.SIC_CD) SICCD,
    F.INDSTRY_TYPE_IND INDTYPEIND,
    TO_CHAR(F.MANL_SIC_FCTR_NBR) MANSICFACTOR,
    TO_CHAR(F.UW_OVERD_SIC_FCTR_NBR) UWOVERDSICFACTOR,
    TO_CHAR(G.AREA_FCTR_NBR) STRAREAFACTOR,
    G.COV_ID COVID,
    F.PLAN_APPRVL_STATUS_CD PLANAPPRVLCD,
    F.PLAN_PROGRS_STATUS_CD PLANPROGRESSSTATUSCD ,
    F.PLAN_SALE_ASSMNT_CD PLANSALEASSMTCD,
    F.CREATD_DT CREATEDDT,
    NVL(to_char(F.PLAN_RELSED_DT),' ') PLANRELSEDDT,
    TO_CHAR(F.PLAN_RELSED_BY_ID) PLANRELSEDBYID,
    TO_CHAR(F.PROPOSD_EFF_DT) PROPOSDEFFECTIVEDT,
    TO_CHAR(A.GRACE_PERIOD_NBR) GRACEPERIOD,
    A.RNWL_15_MONTH_IND FIFTEENMONTHRNWLIND ,
    I.CO_DESC_TXT COMPANYNAME ,
    NVL(to_char(F.PLAN_APPRVL_DT),' ') approvedDt,
                   (Select U.USR_NAME from USR_DETL U WHERE U.USR_ID = F.PLAN_RELSED_BY_ID) as planRelsedByName,
    (Select U.USR_NAME from USR_DETL U WHERE U.USR_ID = F.PLAN_APPRVR_ID) as approvedByName,
    '' createdByName,
    ROWNUM rnum
    FROM
    REQ_FOR_RATING A,
    FIRM B,
    USR_DETL C,          
    SALE_OFFICE D,
    QUOTE_SCENRIO E,
    QUOTE_COV G,
    COV_PLAN F,
    COV_LKUP H,      
    CO_LKUP I
    WHERE
    A.FIRM_ID = B.FIRM_ID AND
    A.SALE_REP_ID = C.USR_ID AND
    C.SALE_OFFC_CD = D.SALE_OFFC_CD AND
    A.REQ_FOR_RATING_ID=E.REQ_FOR_RATING_ID AND
    E.QUOTE_SCENRIO_ID=G.QUOTE_SCENRIO_ID AND
    G.QUOTE_COV_ID=F.QUOTE_COV_ID AND      
    G.COV_ID=H.COV_ID AND
    I.CO_CD = F.CO_CD AND
    TO_CHAR(F.CREATD_DT,'YYYYMMDD') > TO_CHAR(TO_DATE('07/16/2007', 'MM/DD/YYYY HH24:MI:SS'),'YYYYMMDD') AND
    TO_CHAR(F.CREATD_DT,'YYYYMMDD') < TO_CHAR(TO_DATE('10/16/2007', 'MM/DD/YYYY HH24:MI:SS'),'YYYYMMDD')
    and rownum <=?) where rnum >=? Parameters: [07/15/2007 00:00:00, 10/15/2007 23:59:59, 1117, 1]

    That's a SQL fault, not a JDBC/Java fault.

  • Paging data using rownum

    I am trying to fetch a range of data using rownum.
    1. This select statmenet works
    SELECT * from (SELECT id, name, seq from test order by seq desc) where rownum>=1 and rownum<=15
    2. This select statmenet does not work
    SELECT * from (SELECT id, name, seq from test order by seq desc) where rownum>=3 and rownum<=15
    3. This select statment returns wrong rows
    SELECT * from (SELECT id, name, seq, rownum as rn from test order by seq desc) where rn>=3 and rn<=15
    4. This works, but two level deep
    SELECT * from (SELECT id, name, seq, rownum as rn from (SELECT id, name, seq from test order by seq desc)) where rn>=3 and rn<=15
    Is there a better way to fetch a range od data?
    Thanks
    YI

    Generally, we do'nt need the query output based upon rownum because Rownum is determined after the complete resultset has been retrieved, but still if you need the query output based upon Rownum it should be something like this :
    SCOTT@orcl> select empno,rownum from emp;
         EMPNO     ROWNUM
            10          1
          7499          2
          7521          3
          7566          4
          7654          5
          7698          6
          7782          7
          7788          8
          7839          9
          7844         10
          7876         11
         EMPNO     ROWNUM
          7900         12
          7902         13
          7934         14
          9999         15
    15 rows selected.
    SCOTT@orcl> ed
    Wrote file afiedt.buf
      1  select * from ( select empno, row_number() over (order by empno) rorder from emp)
      2* where rorder between 2 and 4
    SCOTT@orcl> /
         EMPNO     RORDER
          7499          2
          7521          3
          7566          4
    SCOTT@orcl>Regards
    Girish harma
    Edited by: Girish Sharma on Mar 26, 2011 5:17 PM

  • How to use Rownum?

    Hi everyone,
    Suppose I am having 100,000 records, and i want to filter only 50,000 records.
    How i can use rownum in OWB.
    I think in join i can use it, other that else any other way
    Regards
    Rachit

    tyr to use a view to reference the data and create rownum along with it.
    in 9.2 we dont have a true support to analytic functions. using a view would be my chocie.

  • Using ROWNUM to split a job in half?

    Hi everyone,
    I have a cursor in which I would like to only select half of the data so that this job can be run in two seperate jobs rather than one large one.
    What is the best way to try this?
    CURSOR C_POPULATE IS
    SELECT TABLE1.ID, TABLE1.CODE, TABLE1.AMT
    FROM   TABLE1, TABLE2
    WHERE  TABLE2.TAB1_ID = TABLE1.IDTABLE2 has an unknown number of TAB1_ID's but only half of them should be selected. These IDs are not in sequence as they are a subgroup of TABLE1.ID taken using a different statement.
    This doesn't work, I know, but something like this added on the end of the cursor:
    AND ROWNUM <= (SELECT CEIL((MAX(ROWNUM)/2)) FROM TABLE2)I know that doesn't work, I'm just using it as an example to show what I mean. Then the second job would be ROWNUM >= etc...
    IS this even going to be possbile using ROWNUM at all? I don't think so.
    What about finding this value - CEIL((MAX(ROWNUM)/2)) - and then putting it in a variable, having a count on every update and putting EXIT WHEN COUNT = V_HALF_ROWNUM?
    If that would work, how would I go about starting the second job?
    Thanks anyone,
    fakelvis

    Maybe this thread will help ...
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:10498431232211
    C.

  • How Oracle returns queries & using rownum

    Hi, I need to limit query results using rownum, but my question is regarding how Oracle retrieves its data.
    Assume I have a table containing 500 records and my query without using rownum will retrieve 62 of those records. The actual query will use rownum and limit results to 20.
    I have a JSP that will display those first 20. It has a simple feature for pagination, a "next" button that will retrieve the next results. So far simple enough, going forwards is easy. But how about going back.
    I am trying to work out the SQL for using a "previous" button, so for example, say records 40-60 are being displayed, and say the first record on that page has a primary key value of 200, what should the SQL be to retrieve the previous 20 records using rownum ? I ask because if I do:
    select * from tablename where pri_key < 200 and rownum <=20;
    I know it will retrieve 20 records, but would the query fetch its results from the beginning of the table or would it count backwards from 200 ? If it is the first way, how could I word the SQL query to go backwards from 200 ? I am pretty sure it will start from the beginning and thats what I don't want. I know there are pagination tags for jsp out there but I want to do this myself.
    Thanks
    Kevin
    Message was edited by:
    MrVen

    First, you need to understand that rownum is only assigned when a record is selected for output, it has nothing to do with any sort of internal order of the table (like insertion order). The same row can have a different rownum even for two invocations of the same query on the same data if the optimizer chooses a different access path. The only way to get a repeatable set of rownum is to sort the records by some field.
    Second, any SQL statement you issue will be executed essentially in isolation. Oracle has no idea what query you executed previously. So, your query:
    SELECT *
    FROM tablename
    WHERE pri_key < 200 and
          rownum <=20;will select a random set of 20 rows wih a primary key less than 200. It is likely to be the first (i.e. lowest values of the pk) rows, but that is not guaranteed.
    The cannonical way to paginate rows is something like:
    SELECT col1, col2, ...
    FROM (SELECT col1, col2, ..., rownum rn
          FROM (SELECT col1, col2, ...
                FROM table
                WHERE <conditions>
                ORDER BY pk) ti
          WHERE rownum <= :maxrownum) to
    WHERE rn >= :minrownumThe innermost query (with the <condition>) selects the appropriate rows and sorts them, in this case by the pk.
    The middle query (rownum <- :maxrownum) discards the rows that would be after the last record you want to display. By using the maxrownum here, it gives Oracle information that allows it to do a fast sort on the inner query if possible.
    In a fast sort, Oracle will get the first maxrownum rows from the query and sort them, then when it gets the next row, it checks if it is less than the highest value already found. If it is, it slots it into the correct place and discards the highest value, otherwise it discards that row.
    The outermost query simply discards the records where the row number after sorting is less than the minimum value.
    Another alternative may be:
    SELECT col1, col2, ...
    FROM (SELECT col1, col2, ...,
                 ROW_NUMBER() OVER(ORDER BY pk) rn
          FROM table
          WHERE <conditions>)
    WHERE rn BETWEEN :minrownum AND :maxrownumdepending on your database version, and your actual query.
    Note tha pagination like this is expensive.
    HTH
    John
    The outermost

Maybe you are looking for

  • Importing from iMovie HD is not bringing any of my edits!

    According to the iMovie 09 help file: "When you import video from iMovie HD projects: - All clips from the clip viewer are added to a new Event. - All clips from the timeline are added to a new project." But when I import, ALL my work is lost. I get

  • Problem with installing and uninstalling applicati...

    hi all, I have a problem with installing or uninstalling apps on 808. When i try to install an application through Nokia suite or when trying to run the application file from the phone's memory the screen freezes and becomes unresponsive but the 3 ph

  • Itunes 7 not playing episodes correctly

    How can I get the TV episodes that I recently purchased to play correctly? Right now they play very choppy and jumpy.

  • Has anyone found a way to save emails to pdf or jpeg

    I need a way to save the email itself from the ipad Mail app.   An example would be the airline reservation emails I receive.  I would like to save these as pdf's. I can copy the contents of the email and paste them into other apps then turn this int

  • How do I find what jars are being used...?

    Hi all, I'm wondering if any of you could help me. I am looking for a method or tool that helps to find what library jars are being used within an application to try and help me erradicate unneccesary files since I find myself in a scenario similar t