HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

create incremental number in oracle sql query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
numbercreatesqlqueryoracleincremental

Problem

how to create incremental number in oracle sql query without create any table ? I have tried using "with" clause, but I failed to get the expected result. I am using oracle 10g

here is the code that I try,it seems not working:

WITH
TABLE3 AS ( SELECT 2008 YEARS FROM dual WHERE 1=1
union all
select t3.YEARS+1 from TABLE3 t3
WHERE 1=1 AND t3.YEARS < 2011
)

select YEARS from TABLE3


expected result I want is :

2008
2009
2010
2011

Solution

I think this will work (based on this page ( http://psoug.org/definition/LEVEL.htm ) as a starting point):

WITH counter
AS ( SELECT LEVEL seq
       FROM DUAL
     CONNECT BY LEVEL <= 4 )
SELECT (2008 + seq - 1) myYear
  FROM counter
 ORDER BY 1
;


This should return:

myYear
------
  2008
  2009
  2010
  2011


Adjust 2008 and 4 to get different results.

Code Snippets

WITH counter
AS ( SELECT LEVEL seq
       FROM DUAL
     CONNECT BY LEVEL <= 4 )
SELECT (2008 + seq - 1) myYear
  FROM counter
 ORDER BY 1
;
myYear
------
  2008
  2009
  2010
  2011

Context

StackExchange Database Administrators Q#3140, answer score: 17

Revisions (0)

No revisions yet.