How do I limit the number of rows returned by an Oracle query after ordering?

前端 未结 17 1548
夕颜
夕颜 2020-11-21 04:56

Is there a way to make an Oracle query behave like it contains a MySQL limit clause?

In MySQL, I can do this:

         


        
相关标签:
17条回答
  • 2020-11-21 05:23

    In case of SQL-Developer, it automatically fetches only first 50 rows. And if we scroll down, it fetches another 50 rows and so on !

    Hence we dont need to define, in case of sql-developer tool !

    0 讨论(0)
  • 2020-11-21 05:23

    (untested) something like this may do the job

    WITH
    base AS
    (
        select *                   -- get the table
        from sometable
        order by name              -- in the desired order
    ),
    twenty AS
    (
        select *                   -- get the first 30 rows
        from base
        where rownum < 30
        order by name              -- in the desired order
    )
    select *                       -- then get rows 21 .. 30
    from twenty
    where rownum > 20
    order by name                  -- in the desired order
    

    There is also the analytic function rank, that you can use to order by.

    0 讨论(0)
  • 2020-11-21 05:25
    select * FROM (SELECT 
       ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
     FROM EMP ) EMP  where ROWID=5
    

    greater then values find out

    select * FROM (SELECT 
           ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
         FROM EMP ) EMP  where ROWID>5
    

    less then values find out

    select * FROM (SELECT 
           ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID, 
         FROM EMP ) EMP  where ROWID=5
    
    0 讨论(0)
  • 2020-11-21 05:25

    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.

      SELECT * FROM sometable1 so
        WHERE so.id IN (
        SELECT so2.id from sometable2 so2
        WHERE ROWNUM <=5
        )
        AND ORDER BY so.somefield AND ROWNUM <= 100 
    

    I have implemented this in oracle server 11.2.0.1.0

    0 讨论(0)
  • 2020-11-21 05:26

    Less SELECT statements. Also, less performance consuming. Credits to: anibal@upf.br

    SELECT *
        FROM   (SELECT t.*,
                       rownum AS rn
                FROM   shhospede t) a
        WHERE  a.rn >= in_first
        AND    a.rn <= in_first;
    
    0 讨论(0)
提交回复
热议问题