Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL (ORACLE): ORDER BY and LIMIT [duplicate]

I want do sorting by property ALL data in my db and ONLY AFTER that use LIMIT and OFFSET.

Query like this:

SELECT select_list     FROM table_expression     [ ORDER BY ... ]     [ LIMIT { number | ALL } ] [ OFFSET number ]  

I know the sorting ends as soon as it has found the first row_count rows of the sorted result. Can I do sorting all data before calling LIMIT and OFFSET?

like image 396
DraggonZ Avatar asked Sep 20 '11 04:09

DraggonZ


People also ask

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

The OFFSET clause specifies the number of rows to skip before the row limiting starts. The OFFSET clause is optional. If you skip it, then offset is 0 and row limiting starts with the first row. The offset must be a number or an expression that evaluates to a number.

Can we use limit in Oracle?

Although it's possible to use limit without an order-by clause, it does not make much sense to do so.

How does Rownum work in Oracle?

You can use ROWNUM to limit the number of rows returned by a query, as in this example: SELECT * FROM employees WHERE ROWNUM < 10; If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed.


1 Answers

Prior to 12.1, Oracle does not support the LIMIT or OFFSET keywords. If you want to retrieve rows N through M of a result set, you'd need something like:

SELECT a.*   FROM (SELECT b.*,                rownum b_rownum           FROM (SELECT c.*                   FROM some_table c                  ORDER BY some_column) b          WHERE rownum <= <<upper limit>>) a  WHERE b_rownum >= <<lower limit>> 

or using analytic functions:

SELECT a.*   FROM (SELECT b.*,                rank() over (order by some_column) rnk           FROM some_table)  WHERE rnk BETWEEN <<lower limit>> AND <<upper limit>>  ORDER BY some_column 

Either of these approaches will sort give you rows N through M of the sorted result.

In 12.1 and later, you can use the OFFSET and/or FETCH [FIRST | NEXT] operators:

SELECT *   FROM some_table  ORDER BY some_column  OFFSET <<lower limit>> ROWS   FETCH NEXT <<page size>> ROWS ONLY 
like image 78
Justin Cave Avatar answered Sep 20 '22 17:09

Justin Cave