Oracle TOP N ordered rows












2














I would like to get the top N rows from an Oracle table sorted by date.



The common way to do this, and this solution returns for every question I could find on SO/google.



Select *
from
(select * from
myTable
ordered by Date desc)
where rownum < N


This solution is in my case impracticable because myTable contains an huge ammount of rows which would
lead to Oracle taking too long to return all rows in the subquery.



Question is, is there a way to limit the number of ORDERED rows returned in the subquery ?










share|improve this question



























    2














    I would like to get the top N rows from an Oracle table sorted by date.



    The common way to do this, and this solution returns for every question I could find on SO/google.



    Select *
    from
    (select * from
    myTable
    ordered by Date desc)
    where rownum < N


    This solution is in my case impracticable because myTable contains an huge ammount of rows which would
    lead to Oracle taking too long to return all rows in the subquery.



    Question is, is there a way to limit the number of ORDERED rows returned in the subquery ?










    share|improve this question

























      2












      2








      2







      I would like to get the top N rows from an Oracle table sorted by date.



      The common way to do this, and this solution returns for every question I could find on SO/google.



      Select *
      from
      (select * from
      myTable
      ordered by Date desc)
      where rownum < N


      This solution is in my case impracticable because myTable contains an huge ammount of rows which would
      lead to Oracle taking too long to return all rows in the subquery.



      Question is, is there a way to limit the number of ORDERED rows returned in the subquery ?










      share|improve this question













      I would like to get the top N rows from an Oracle table sorted by date.



      The common way to do this, and this solution returns for every question I could find on SO/google.



      Select *
      from
      (select * from
      myTable
      ordered by Date desc)
      where rownum < N


      This solution is in my case impracticable because myTable contains an huge ammount of rows which would
      lead to Oracle taking too long to return all rows in the subquery.



      Question is, is there a way to limit the number of ORDERED rows returned in the subquery ?







      sql oracle






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 28 '11 at 11:40









      Oysio

      1,68463451




      1,68463451
























          4 Answers
          4






          active

          oldest

          votes


















          12














          Your inference that Oracle must return all rows in the subquery before filtering out the first N is wrong. It will start fetching rows from the subquery, and stop when it has returned N rows.



          Having said that, it may be that Oracle needs to select all rows from the table and sort them before it can start returning them. But if there were an index on the column being used in the ORDER BY clause, it might not.



          Oracle is in the same position as any other DBMS: if you have a large table with no index on the column you are ordering by, how can it possibly know which rows are the top N without first getting all the rows and sorting them?






          share|improve this answer































            2















            Question is, is there a way to limit the number of ORDERED rows
            returned in the subquery ?




            The following is what I typically use for top-n type queries (pagination query in this case):



            select * from (
            select a.*, rownum r
            from (
            select *
            from your_table
            where ...
            order by ...
            ) a
            where rownum <= :upperBound
            )
            where r >= :lowerBound;


            I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:



            create table t3 as select * from all_objects;
            alter table t3 add constraint t_pk primary key(object_id);
            analyze table t3 compute statistics;

            delete from plan_table;
            commit;
            explain plan for
            select * from (
            select a.*, rownum r
            from (
            select object_id, object_name
            from t3
            order by object_id
            ) a
            where rownum <= 2000
            )
            where r >= 1;

            select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
            from plan_table
            order by id;


            You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.



            Hope that explains my answer ;)






            share|improve this answer



















            • 1




              You should explain why you think this is a suitable answer to the question.
              – Allan
              Jul 28 '11 at 14:59



















            1














            Order by may become heavy operation if you have lots of data. Take a look at your execution plan. If the data is not real time you could create a material view on these kind of selects...






            share|improve this answer





























              0














              In older versions of ORACLE (8.0) you don't have the possibility to use ORDER BY clause in subquery.
              So, only for those of us who yet use some ancient versions, there is another way to deal with: The magic of UNION operator.
              UNION will sort the records by columns in the query:



              Example:



              SELECT * FROM
              (SELECT EMP_NO, EMP_NAME FROM EMP_TABLE
              UNION
              SELECT 99999999999,'' FROM DUAL)
              WHERE ROWNUM<=5
              where 99999999999 is bigger then all values in EMP_NO;


              Or, if you want to select TOP 5 salary employees with the highest 5 salaries:



              SELECT EMP_NO, EMP_NAME, 99999999999999-TMP_EMP_SAL
              FROM
              (SELECT 99999999999999-EMP_SAL TMP_EMP_SAL, EMP_NO, EMP_NAME
              FROM EMP_TABLE
              UNION
              SELECT 99999999999999,0,'' FROM DUAL)
              WHERE ROWNUM<=5;


              Regards,



              Virgil Ionescu






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6858325%2foracle-top-n-ordered-rows%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                12














                Your inference that Oracle must return all rows in the subquery before filtering out the first N is wrong. It will start fetching rows from the subquery, and stop when it has returned N rows.



                Having said that, it may be that Oracle needs to select all rows from the table and sort them before it can start returning them. But if there were an index on the column being used in the ORDER BY clause, it might not.



                Oracle is in the same position as any other DBMS: if you have a large table with no index on the column you are ordering by, how can it possibly know which rows are the top N without first getting all the rows and sorting them?






                share|improve this answer




























                  12














                  Your inference that Oracle must return all rows in the subquery before filtering out the first N is wrong. It will start fetching rows from the subquery, and stop when it has returned N rows.



                  Having said that, it may be that Oracle needs to select all rows from the table and sort them before it can start returning them. But if there were an index on the column being used in the ORDER BY clause, it might not.



                  Oracle is in the same position as any other DBMS: if you have a large table with no index on the column you are ordering by, how can it possibly know which rows are the top N without first getting all the rows and sorting them?






                  share|improve this answer


























                    12












                    12








                    12






                    Your inference that Oracle must return all rows in the subquery before filtering out the first N is wrong. It will start fetching rows from the subquery, and stop when it has returned N rows.



                    Having said that, it may be that Oracle needs to select all rows from the table and sort them before it can start returning them. But if there were an index on the column being used in the ORDER BY clause, it might not.



                    Oracle is in the same position as any other DBMS: if you have a large table with no index on the column you are ordering by, how can it possibly know which rows are the top N without first getting all the rows and sorting them?






                    share|improve this answer














                    Your inference that Oracle must return all rows in the subquery before filtering out the first N is wrong. It will start fetching rows from the subquery, and stop when it has returned N rows.



                    Having said that, it may be that Oracle needs to select all rows from the table and sort them before it can start returning them. But if there were an index on the column being used in the ORDER BY clause, it might not.



                    Oracle is in the same position as any other DBMS: if you have a large table with no index on the column you are ordering by, how can it possibly know which rows are the top N without first getting all the rows and sorting them?







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 28 '11 at 13:00

























                    answered Jul 28 '11 at 11:43









                    Tony Andrews

                    107k17189233




                    107k17189233

























                        2















                        Question is, is there a way to limit the number of ORDERED rows
                        returned in the subquery ?




                        The following is what I typically use for top-n type queries (pagination query in this case):



                        select * from (
                        select a.*, rownum r
                        from (
                        select *
                        from your_table
                        where ...
                        order by ...
                        ) a
                        where rownum <= :upperBound
                        )
                        where r >= :lowerBound;


                        I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:



                        create table t3 as select * from all_objects;
                        alter table t3 add constraint t_pk primary key(object_id);
                        analyze table t3 compute statistics;

                        delete from plan_table;
                        commit;
                        explain plan for
                        select * from (
                        select a.*, rownum r
                        from (
                        select object_id, object_name
                        from t3
                        order by object_id
                        ) a
                        where rownum <= 2000
                        )
                        where r >= 1;

                        select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
                        from plan_table
                        order by id;


                        You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.



                        Hope that explains my answer ;)






                        share|improve this answer



















                        • 1




                          You should explain why you think this is a suitable answer to the question.
                          – Allan
                          Jul 28 '11 at 14:59
















                        2















                        Question is, is there a way to limit the number of ORDERED rows
                        returned in the subquery ?




                        The following is what I typically use for top-n type queries (pagination query in this case):



                        select * from (
                        select a.*, rownum r
                        from (
                        select *
                        from your_table
                        where ...
                        order by ...
                        ) a
                        where rownum <= :upperBound
                        )
                        where r >= :lowerBound;


                        I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:



                        create table t3 as select * from all_objects;
                        alter table t3 add constraint t_pk primary key(object_id);
                        analyze table t3 compute statistics;

                        delete from plan_table;
                        commit;
                        explain plan for
                        select * from (
                        select a.*, rownum r
                        from (
                        select object_id, object_name
                        from t3
                        order by object_id
                        ) a
                        where rownum <= 2000
                        )
                        where r >= 1;

                        select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
                        from plan_table
                        order by id;


                        You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.



                        Hope that explains my answer ;)






                        share|improve this answer



















                        • 1




                          You should explain why you think this is a suitable answer to the question.
                          – Allan
                          Jul 28 '11 at 14:59














                        2












                        2








                        2







                        Question is, is there a way to limit the number of ORDERED rows
                        returned in the subquery ?




                        The following is what I typically use for top-n type queries (pagination query in this case):



                        select * from (
                        select a.*, rownum r
                        from (
                        select *
                        from your_table
                        where ...
                        order by ...
                        ) a
                        where rownum <= :upperBound
                        )
                        where r >= :lowerBound;


                        I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:



                        create table t3 as select * from all_objects;
                        alter table t3 add constraint t_pk primary key(object_id);
                        analyze table t3 compute statistics;

                        delete from plan_table;
                        commit;
                        explain plan for
                        select * from (
                        select a.*, rownum r
                        from (
                        select object_id, object_name
                        from t3
                        order by object_id
                        ) a
                        where rownum <= 2000
                        )
                        where r >= 1;

                        select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
                        from plan_table
                        order by id;


                        You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.



                        Hope that explains my answer ;)






                        share|improve this answer















                        Question is, is there a way to limit the number of ORDERED rows
                        returned in the subquery ?




                        The following is what I typically use for top-n type queries (pagination query in this case):



                        select * from (
                        select a.*, rownum r
                        from (
                        select *
                        from your_table
                        where ...
                        order by ...
                        ) a
                        where rownum <= :upperBound
                        )
                        where r >= :lowerBound;


                        I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:



                        create table t3 as select * from all_objects;
                        alter table t3 add constraint t_pk primary key(object_id);
                        analyze table t3 compute statistics;

                        delete from plan_table;
                        commit;
                        explain plan for
                        select * from (
                        select a.*, rownum r
                        from (
                        select object_id, object_name
                        from t3
                        order by object_id
                        ) a
                        where rownum <= 2000
                        )
                        where r >= 1;

                        select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
                        from plan_table
                        order by id;


                        You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.



                        Hope that explains my answer ;)







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jul 28 '11 at 17:49

























                        answered Jul 28 '11 at 14:37









                        tbone

                        11.9k12436




                        11.9k12436








                        • 1




                          You should explain why you think this is a suitable answer to the question.
                          – Allan
                          Jul 28 '11 at 14:59














                        • 1




                          You should explain why you think this is a suitable answer to the question.
                          – Allan
                          Jul 28 '11 at 14:59








                        1




                        1




                        You should explain why you think this is a suitable answer to the question.
                        – Allan
                        Jul 28 '11 at 14:59




                        You should explain why you think this is a suitable answer to the question.
                        – Allan
                        Jul 28 '11 at 14:59











                        1














                        Order by may become heavy operation if you have lots of data. Take a look at your execution plan. If the data is not real time you could create a material view on these kind of selects...






                        share|improve this answer


























                          1














                          Order by may become heavy operation if you have lots of data. Take a look at your execution plan. If the data is not real time you could create a material view on these kind of selects...






                          share|improve this answer
























                            1












                            1








                            1






                            Order by may become heavy operation if you have lots of data. Take a look at your execution plan. If the data is not real time you could create a material view on these kind of selects...






                            share|improve this answer












                            Order by may become heavy operation if you have lots of data. Take a look at your execution plan. If the data is not real time you could create a material view on these kind of selects...







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 28 '11 at 11:51









                            Dmitry Alexandrov

                            325114




                            325114























                                0














                                In older versions of ORACLE (8.0) you don't have the possibility to use ORDER BY clause in subquery.
                                So, only for those of us who yet use some ancient versions, there is another way to deal with: The magic of UNION operator.
                                UNION will sort the records by columns in the query:



                                Example:



                                SELECT * FROM
                                (SELECT EMP_NO, EMP_NAME FROM EMP_TABLE
                                UNION
                                SELECT 99999999999,'' FROM DUAL)
                                WHERE ROWNUM<=5
                                where 99999999999 is bigger then all values in EMP_NO;


                                Or, if you want to select TOP 5 salary employees with the highest 5 salaries:



                                SELECT EMP_NO, EMP_NAME, 99999999999999-TMP_EMP_SAL
                                FROM
                                (SELECT 99999999999999-EMP_SAL TMP_EMP_SAL, EMP_NO, EMP_NAME
                                FROM EMP_TABLE
                                UNION
                                SELECT 99999999999999,0,'' FROM DUAL)
                                WHERE ROWNUM<=5;


                                Regards,



                                Virgil Ionescu






                                share|improve this answer




























                                  0














                                  In older versions of ORACLE (8.0) you don't have the possibility to use ORDER BY clause in subquery.
                                  So, only for those of us who yet use some ancient versions, there is another way to deal with: The magic of UNION operator.
                                  UNION will sort the records by columns in the query:



                                  Example:



                                  SELECT * FROM
                                  (SELECT EMP_NO, EMP_NAME FROM EMP_TABLE
                                  UNION
                                  SELECT 99999999999,'' FROM DUAL)
                                  WHERE ROWNUM<=5
                                  where 99999999999 is bigger then all values in EMP_NO;


                                  Or, if you want to select TOP 5 salary employees with the highest 5 salaries:



                                  SELECT EMP_NO, EMP_NAME, 99999999999999-TMP_EMP_SAL
                                  FROM
                                  (SELECT 99999999999999-EMP_SAL TMP_EMP_SAL, EMP_NO, EMP_NAME
                                  FROM EMP_TABLE
                                  UNION
                                  SELECT 99999999999999,0,'' FROM DUAL)
                                  WHERE ROWNUM<=5;


                                  Regards,



                                  Virgil Ionescu






                                  share|improve this answer


























                                    0












                                    0








                                    0






                                    In older versions of ORACLE (8.0) you don't have the possibility to use ORDER BY clause in subquery.
                                    So, only for those of us who yet use some ancient versions, there is another way to deal with: The magic of UNION operator.
                                    UNION will sort the records by columns in the query:



                                    Example:



                                    SELECT * FROM
                                    (SELECT EMP_NO, EMP_NAME FROM EMP_TABLE
                                    UNION
                                    SELECT 99999999999,'' FROM DUAL)
                                    WHERE ROWNUM<=5
                                    where 99999999999 is bigger then all values in EMP_NO;


                                    Or, if you want to select TOP 5 salary employees with the highest 5 salaries:



                                    SELECT EMP_NO, EMP_NAME, 99999999999999-TMP_EMP_SAL
                                    FROM
                                    (SELECT 99999999999999-EMP_SAL TMP_EMP_SAL, EMP_NO, EMP_NAME
                                    FROM EMP_TABLE
                                    UNION
                                    SELECT 99999999999999,0,'' FROM DUAL)
                                    WHERE ROWNUM<=5;


                                    Regards,



                                    Virgil Ionescu






                                    share|improve this answer














                                    In older versions of ORACLE (8.0) you don't have the possibility to use ORDER BY clause in subquery.
                                    So, only for those of us who yet use some ancient versions, there is another way to deal with: The magic of UNION operator.
                                    UNION will sort the records by columns in the query:



                                    Example:



                                    SELECT * FROM
                                    (SELECT EMP_NO, EMP_NAME FROM EMP_TABLE
                                    UNION
                                    SELECT 99999999999,'' FROM DUAL)
                                    WHERE ROWNUM<=5
                                    where 99999999999 is bigger then all values in EMP_NO;


                                    Or, if you want to select TOP 5 salary employees with the highest 5 salaries:



                                    SELECT EMP_NO, EMP_NAME, 99999999999999-TMP_EMP_SAL
                                    FROM
                                    (SELECT 99999999999999-EMP_SAL TMP_EMP_SAL, EMP_NO, EMP_NAME
                                    FROM EMP_TABLE
                                    UNION
                                    SELECT 99999999999999,0,'' FROM DUAL)
                                    WHERE ROWNUM<=5;


                                    Regards,



                                    Virgil Ionescu







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Dec 27 '18 at 21:29









                                    ltd9938

                                    9451822




                                    9451822










                                    answered Dec 27 '18 at 18:15







                                    user10840231





































                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6858325%2foracle-top-n-ordered-rows%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Angular Downloading a file using contenturl with Basic Authentication

                                        Olmecas

                                        Can't read property showImagePicker of undefined in react native iOS