Wednesday, May 27, 2015

Using rownum and order-by

If you try to use rownum and order-by in a select statement, maybe the result will not match with your expectation. It is because the order-by is one of the last operation in the queue.

Using rownum function


The query:
SELECT ROWNUM,
       T.DOMA_KY,
       T.SHORT_DESCRIPTION_LB
  FROM T_DOMAIN T
 WHERE T.ACRONYM_CD = 'PLCY'
 ORDER BY T.DOMA_KY


    ROWNUM DOMA_KY SHORT_DESCRIPTION_LB
1 6 261 P1-Jobs, Growth and Investment
2 2 262 P2-Digital Single Market
3 4 263 P3-Energy Union and Climate
4 8 264 P4-Internal Market
5 3 265 P5-Economic and Monetary Union
6 10 266 P6-EU-US Free Trade
7 7 267 P7-Justice and Fundamental Rights
8 9 268 P8-Migration
9 5 269 P9-EU as Global Actor
10 1 270 P10-Democratic Change

Using row_number() function


The query:
SELECT ROW_NUMBER() OVER (ORDER BY T.DOMA_KY) ROW_NUMBER,
       T.DOMA_KY,
       T.SHORT_DESCRIPTION_LB,
       T.ROWID
  FROM T_DOMAIN T
 WHERE T.ACRONYM_CD = 'PLCY'
 ORDER BY T.DOMA_KY

    ROW_NUMBER DOMA_KY SHORT_DESCRIPTION_LB
1 1 261 P1-Jobs, Growth and Investment
2 2 262 P2-Digital Single Market
3 3 263 P3-Energy Union and Climate
4 4 264 P4-Internal Market
5 5 265 P5-Economic and Monetary Union
6 6 266 P6-EU-US Free Trade
7 7 267 P7-Justice and Fundamental Rights
8 8 268 P8-Migration
9 9 269 P9-EU as Global Actor
10 10 270 P10-Democratic Change

No comments:

Post a Comment