Factorial in SQL

Example for versions Oracle 10g SQL, Oracle 11g SQL

This example shows the use of model clause, available since Oracle 10g. It allows array-like processing of query rows. Each row has two columns — iteration number (stored in n) and its factorial (stored in f).

select n || '! = ' || f factorial
  from dual
 model
    return all rows
    dimension by ( 0 d ) 
    measures ( 0 f, 1 n )
    rules iterate (17)
    ( f[iteration_number] = decode(iteration_number, 0, 1, f[iteration_number-1]*iteration_number),
      n[iteration_number] = iteration_number
    );