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

Similar Messages

  • How to return integer used wit DMBS_SQL as ref cursor ?

    I am trying to return a ref cursor form a procedure to be used by xsql to output hierarchical XML.
    I created the query using the DBMS_SQL package, did an OPEN_CURSOR and then PARSE.
    Can I, and if so how, return the integer from the PARSE as a ref cursor out of my procedure ? According to the docs the integer in the PARSE is the ID number for a cursor.
    thanks,
    Reinier

    I suspect that you are a little confused. I doubt that what you are asking for is what you really need. I believe you want the contents of a ref cursor, not an integer that is the cursor id. Since you are using Oracle 8i, as mentioned in your other post, you don't need DBMS_SQL; You just need to open a ref cursor dynmacially. Please see my response to your other post:
    Re: Error while compiling form in AS 10g  deployed on Linux

  • 11g Database Adapter: How to make queries using LIKE with % (possible bug?)

    Hi there!
    Sorry if this has been answered before, but the forum search ignores '%' so I could not find anything relevant. I'm completely at a loss here guys so any help will be really appreciated.
    I've got a database adapter that executes a "pure SQL" query:
    select * from supplier t
    WHERE t.idsupplier = #idSupplierParam OR #idSupplierParam2 IS NULL
    AND t.name like '%' || #nameParam || '%' OR #nameParam2 IS NULL
    AND t.address like '%' || #addressParam || '%' OR #addressParam2 IS NULL
    AND t.description like '%' || #descParam || '%' OR #descParam2 IS NULL
    I've got a single record in my DB with name= 'supplier1'
    When I execute my bpel passing 'sup' as nameParam and nameParam2, everything is right and I get my supplier1 in the results.
    BUT if I pass 'asdfghj' as name, I still get my 'supplier1' in the results ¿¿¿???
    ¿Is this a bug? ¿Am I doing something wrong? Thanks in advance!!

    No, but thanks for trying. Iif you had read my post you'd had found that I wrote
    +When I execute my bpel passing 'sup' as nameParam and nameParam2+
    But I double checked against that just in case. I made a test query
    select * from supplier t WHERE t.name like '%' || #nameParam || '%'
    And no matter what I pass as nameParam, I always GET ALL THE RECORDS in my table. ¿Any idea what's going on? It's like param is being ignored and the query that is executed is select * from supplier t WHERE t.name like '%%' which would of course return everything in the DB. :(
    Help plz!!

  • How to return a set of data  by using webservice ?

    Hi.
    I am finding how to return a set of data by using java webservice that serves clients written by others such as VB. Net. Please help me !
    Thanks in advance.

    Check the how to on Accessing Oracle9iAS Java Web Service from a .NET Client
    http://otn.oracle.com/sample_code/tech/java/codesnippet/webservices/index.html
    Chandar

  • How oracle replaces "carrage return, tab and blank" in v$sql.sql_text??

    Hi. all.
    I am wondering how oracle replace "carrage return, tab and blank" character to v$sql.sql_text??
    I am try to find sql_id by the following query.
    select * from v$sql where sql_text like 'blur blur %'.
    However, how can I specify 'blur blur %' when the original sql text includes "carrage return, tab, amd double blank"?
    To be more specific,
    the original sql statement:
    select
    col_a,
    col_b , -- tab character included
    colc , -- more than one blank included
    Then, how can I specifiy "sql_text like 'blur blur %'" ??
    As far as I know, oracle replace "carrage return, tab, and more than one blank" to "ONE BLANK" character.
    Is this right???
    Thanks in advance.
    Best Regards.

    Oracle simply unformat the SQL text and put it into v$sql.sql_text because SQL formatting is only for reading and clearity purpose. It don't help to generate SQL_ID and execution plan. You may get couple of freely avilable SQL formatting tool on the internet, you can simply copy SQL_TEXT and if you paste them into those tool, they will auto format, tab, upper and lower case of required words.
    If you find this reply helpful or correct, please mark accordingly because you asked 17 questions and zero answerred. This seems that this forum is 0% useful to you! (sad)
    Regards
    Girish Sharma

  • How to Return a value to a 10g Oracle Form form a Web Service Call

    I've read the demo available from Oracle, 'Calling a Web service from Oracle Forms', that shows how to invoke a call to a Web Service from a Form. The demo only shows how to do a call and how to display messages. I've done some searching, but can't seem to find any examples of how to return a value from the call into a field on the form. If any one could provide an example of that, I would greatly appreciate it.
    We are in the process of modifing a form and we would like to use a webservice, which we have never done before. We have created a webservice which calculates a value based upon what is entered on the form and we want to pass that calculated value back to a field on the form.
    This is the code provided by the demo to do a call.
    DECLARE
    jo ora_java.jobject;
    xo ora_java.jobject;
    rv varchar2(100);
    ex ora_java.jobject;
    BEGIN
    JO := SendServiceSoapClient.new;
    RV := SendServiceSoapClient.sendMessage(JO,:BLOCK3.PHONE_NUMBER, :BLOCK3.MESSAGE_BODY, xo, xo);
    EXCEPTION
    WHEN ORA_JAVA.JAVA_ERROR then
    message('Unable to call out to Java, ' ||ORA_JAVA.LAST_ERROR);
    WHEN ORA_JAVA.EXCEPTION_THROWN then
    ex := ORA_JAVA.LAST_EXCEPTION;
    message(Exception_.toString(ex));
    END;

    In the future, please be sure to include the exact product versions you are using. In this case, also be sure to include the java versions you are using to build your java code.
    http://blogs.oracle.com/shay/entry/10_commandments_for_the_otn_fo
    Regarding your question, take a look at this older white paper which discusses integrating Forms with SOA.
    http://www.oracle.com/technetwork/developer-tools/forms/documentation/forms-soa-wp-1-129441.pdf

  • How do you query Oracle RDF database using Java program?

    Does anyone know how to get data out of the oracle RDF database using Java?
    I'm running the following java code and it returns basically null values. My guess is that the get_triple() function returns a dataset other than resultset. I've tried searching the Oracle web site. Am I supposed to be using CLOB object? Any help would be appreciated. Thanks
    sql = "SELECT a.triple.GET_TRIPLE() AS triple FROM family_rdf_data a";
    ResultSet rs = stmt.executeQuery( sql ) ;
    while ( rs.next() )
    System.out.println( rs.getString(1) ) ;
    rs.close() ;

    get_triple() returns an object, and the code would be different from the code of retrieving a string. Some sample code for retrieving objects is at http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/advanced.html
    get_subject(), get_property() return strings so the code below should work. get_object() returns a CLOB so different handling would be required and there is some sample code at the link above.
    Melli

  • How to configure oracle alerts to use Workflow mailer?

    Hello Guys:
    We were trying to setup oracle alerts using workflow mailer. I have created a dedicated mailer for handling oracle alerts related mail.
    Here is what I need to clarify:
    1. Having setup a new mailer for Oracle alert do I have to still configure the Options in Oracle Alerts. This is where you choose which type of mail u want to use ( like Unix mail,Windows NT mail )
    2.How do I tell oracle alert to use the new mailer that I created exclusively for this? While creating the mailer at some point I remember putting ALR in configuration form.
    I am on 11.5.10 CU2. I am on 11i.ATG_PF.H
    Regards,
    Bala

    Hi Hussain:
    Based on the note I realised that my oracle alerts will user unix sendmail. But then If u go to " Oracle Alert Options "
    -- > Mail systems -- I check Unix send mail
    -- > Mail server options ( Do I have to fill this section? )
    My guess is that the send mail will post the email to a IMAP account ( I created oraclealert account ) and IMAP account will push the alert email to Recipient
    Mail Database/Server Name --- imap.mydomain.com
    Mail Priority --- Normal
    Accounts
    Application Installation username Password
    Blank ** Blank ** oraclealert pwd
    Blank ** Blank ** oraclealert pwd
    ** - It wont allow me to choose an application.
    Is there a simple test to make sure that my oracle alert is working or not? I appreciate your help.
    Regards,
    Bala

  • How to find out the top 20 queries used in a week

    Hi Guru's,
    I would like to know how to gather the information regarding the Top 20 queries used in the system per week, by a multicube.
    Note: I am using BI 7.0 and also Statistics are turned on.
    The aim is to pre-calculate these queries at night to help with the user experience.
    Thanks and regards,

    Hi
    U can check in RSZCOMPDIR if u did not find the info then go to se11 and give RSZ* and press F4 u will get all the tables which relates to reports
    Assign points if it helps
    Khaja

  • How can I return to use OSX (Yosemite) after installing Windows 8.1?

    How can I return to use OSX (Yosemite) after installing Windows 8.1?
    I cannot find Boot Camp on my iMac (late 2013) with windows installed. So I downloaded it, but I cannot run it because of an error (x64...). I tried to use my USB stick with bootcamp installed but nothing. When I turn my iMac on it starts automatically with windows. I tried to search it, but I found only the setup and it doesn't work. How can I get back to my APPLE iMac? How can I use OSX?
    Excuse me for the (maybe) uncorrect language, I speak Italian.

    Hello!
    You can start your Mac up with the [alt] (sometimes [option]) key pressed and you will get the Startup Manager.

  • How to replace numbers with text in tax return pdf using Adobe Acrobat X Pro

    How do I replace numbers with text in tax return pdf using Adobe Acrobat X Pro? The tax return was created using CCH software. Thanks for your review.

    Thanks Bill for your quick reply. CCH software is one of the major
    suppliers of tax return software. I found an internal source that helped me
    make the changes from numbers to text i.e. "$123,456" to "See Schedule O".
    I am not sure if I am working in form or final text. Thanks again! Kelly

  • How to upload data into form of Oracle EBS R12 using ATS ver 9.0

    Hi experts,
    Could you please guide me how to upload data into form on Oracle EBS R12 using Oracle Application Testing Suite verson 9.(The simpliest way)
    For example: I need to create user account on Oracle EBS. Normally, I use Dataloader to upload the data, however it just can upload one by one record, cannot upload multi record at same time. Moreover if the performance of server is low, so I will get the issue when using dataloader.
    Thanks in advance
    Best Regards
    Hieu

    Hi you can create Virtual users to enter data. Note than you have to name the objects accordingly.
    For Example default recording provided by Open script is ObjectNAME_(Index No of the object).
    when you record one iteration the name of any object would be ObjectNAME_(0)
    You can then create virtual users so the index will increment as the total number of Virtual users increases. Also you have to handle which row of your test data would get mapped to which Virtual user in the script run session.
    Thanks

  • How to return a pdf (iText) file using Portlet?

    Dear all,
    I want to know how to return a pdf file using iText API via Portlet.
    I can manage to return a pdf file through a standalone servlet, but I don't have idea of how to generate a pdf file via Portlet.
    Can anyone help me?
    Thanks
    George (HK)
    Welcome to my blog at www.xanga.com/georgelkh

    Hello,
    that is easy. In your driver program, please check the inputs of the job/ generator function modules.
    You provide GETPDF = 'X' attribute what will make the FM not to print the form or display the preview but to return the binary stream of the PDF data (type FPCONTENT) what is a RAW or something. Next look for the PDF output parameter to get the returned binary data and send it as you wish through JCo.
    Regards Otto
    p.s.: Note there is Adobe forms forum under NetWeaver, you can find me and the others doing Adobe every day

  • How to import custom java jar/class into oracle to be used in java proc ?

    Hi
    I would like to know how to import custom java jar/class files into oracle to be used in java stored procedure.
    I am developing a oracle pl/sql procedure to call java program. The java program will be created as procedure and will be published.
    But, my question is that I do have a other external jar/class file that need to be imported into this java program.
    example
    raise_sal.java
    import java.util.*;
    import oracle.sql.*;
    <<reference other java programs >>
    import cmpmsgsvc.xxxx.* ;
    import cmpmsgsvc.yyyy.* ;
    import cmpmsgsvc.zzzz.* ;
    how do I import the cmpmsgsvc jar/class file into oracle so that I don't have any
    compilation errros on raise_sal.java program ??
    what are the steps to import/compile and validate to do this?
    thanks for your help in advance.
    Thanks
    rrb.

    Kuassi
    Problem is that, I have 6 jar files that are needed to be included in the main java program. And, there are more than 50+ classes, propertiers in those 6 jar files.
    It might be not good idea to have all those 50+ classes in the production database.
    Is there anyway that I keep all those 6 jar files in unix box (our's is oracle erp installation with oracle being installed on unix box) and just refer them in the main java program. I mean database will be loaded with main java program and it should able to refer other 6 jar files from unix.
    if we create a directory and keep all jar files in there and include that directory in classpath variable, does this works? or what is other method?
    Please let me know.
    Thanks

  • How i can deal with oracle file by using php api

    how I can deal with oracle file by using php api ?

    What has this to do with Reflections and Reference Objects?

Maybe you are looking for

  • Error in cancelling Intercompany Invoice

    Hi, A fatal error has occurred in the Production System.The is part of the Intercompany flow. -Sales order is raised for a customer belonging to Sales Organization A. -Delivery is made directly to customer of Sales Org A from a Plant belonging to Sal

  • Converting to Shared Services Security Mode Error (externalize users)

    Error: 1051549: Can not convert Analytic Services to Shared Services mode when Analytic Services is not configured with Shared Services or the initialization process has failed I have tried to register ESSbase with SS again and does not work. All ser

  • Where can I download Group Policy Health Check Tool v.1.0?

    I once saw a screenshot of this tool (Group Policy Health Check Tool v.1.0) from some document.  However, when I search on line for it, it looks like this tool simply does not exist.  Can someone help me?

  • How do I cascade Mozilla windows in Windows 7 desktop

    In older versions when many Firefox windows were open, the option to cascade the windows was available. On this PC with Windows 7 this option seems to have disappeared. Also, it used to be possible to close all Firefox windows at once, and now they h

  • How do you identify which version Sansa you have while it's a brick?

    Got a 280R (Rhapsody), and I'm pretty sure it's version 1, but not positive. Couldn't restore it, so went to Recovery mode. I want to try and salvage it, but don't want to load the wrong firmware. Any ideas? Thx!