Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: Display row number with 'order by' clause

Tags:

sql

oracle

I wonder how could i print a row number for sql statement where is using order. Currently i tried ROWNUM but as i understand it works only for unsorted result set.

SELECT rownum, a.lg_id, a.full_name, a.sort_order
  FROM activity_type_lang a
  where a.lg_id = 'en'
  order by a.full_name;

TIA

like image 698
Igor Konoplyanko Avatar asked Sep 04 '09 08:09

Igor Konoplyanko


People also ask

How use Rownum with ORDER BY in SQL?

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.

What is ROW_NUMBER () over ORDER BY column?

ROW_NUMBER() Function The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows.

How can I get row number in PL SQL?

Description. The Oracle/PLSQL ROWNUM function returns a number that represents the order that a row is selected by Oracle from a table or joined tables. The first row has a ROWNUM of 1, the second has a ROWNUM of 2, and so on.

Can I use row number in WHERE clause?

The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.


1 Answers

In addition to nesting the query, you can use an analytic function

SELECT row_number() OVER (ORDER BY a.full_name),
       lg_id,
       full_name,
       sort_order
  FROM activity_type_lang a
 WHERE a.lg_id = 'en'
 ORDER BY a.full_name

Using analytic functions also makes it easier if you want to change how ties are handled. You can replace ROW_NUMBER with RANK or DENSE_RANK.

like image 135
Justin Cave Avatar answered Oct 20 '22 03:10

Justin Cave