Skip to main content
← PL/SQL Topics

Packages & Modularity

Explain recursive subprograms in PL/SQL

Recursive Subprograms

ExplanationOracle Fusion / EBS · Technical · PL/SQLHigh confidenceGenerated

A subprogram may call itself; each call gets its own copy of parameters and local variables on the stack.

How it works

Recursion works in PL/SQL like any language: define a base case that returns without recursing, and a recursive case that moves toward it. Each invocation has its own locals. Depth is bounded by the PL/SQL stack, so very deep recursion (tens of thousands of frames) can raise ORA-06500 / storage errors — an iterative version or a hierarchical SQL query (CONNECT BY / recursive WITH) is better for deep tree walks.

How it works
CREATE OR REPLACE FUNCTION factorial(p_n PLS_INTEGER) RETURN NUMBER IS
BEGIN
  IF p_n <= 1 THEN
    RETURN 1;                       -- base case
  ELSE
    RETURN p_n * factorial(p_n - 1);  -- recursive case
  END IF;
END;
/
SELECT factorial(10) FROM dual;   -- 3628800

Related questions

GroundingGenerated

Model-generated, grounded against the curated knowledge layer. Check specifics against your instance.

Have a follow-up, or a different question?

Continue in Ask Oracle AI