SQL Tutorial

SQL Clauses / Operators

SQL-Injection

SQL Functions

SQL Queries

PL/SQL

MySQL

SQL Server

Misc

Finding sum of first n natural numbers in PL/SQL

To find the sum of the first n natural numbers, you can make use of a well-known formula:

Sum=2n×(n+1)​

However, if you'd like to use a loop to compute this sum iteratively in PL/SQL, you can do that too. Below are both approaches:

  • Using the Formula:
DECLARE 
    n NUMBER := 100; -- Change this value for different results
    sum_val NUMBER;
BEGIN 
    sum_val := n * (n + 1) / 2;
    DBMS_OUTPUT.PUT_LINE('Sum of first ' || n || ' natural numbers is: ' || sum_val);
END;
/
  • Iterative Approach:
DECLARE 
    n NUMBER := 100; -- Change this value for different results
    sum_val NUMBER := 0;
    i NUMBER;
BEGIN 
    FOR i IN 1..n LOOP
        sum_val := sum_val + i;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('Sum of first ' || n || ' natural numbers is: ' || sum_val);
END;
/

You can adjust the value of n in either script to compute the sum for a different number of natural numbers. The formula-based approach is more efficient, especially for larger values of n, as it avoids iteration.

  1. PL/SQL Procedure for Sum of First n Numbers:

    CREATE OR REPLACE PROCEDURE CalculateSum(p_n IN NUMBER) IS
        v_sum NUMBER := 0;
    BEGIN
        FOR i IN 1..p_n LOOP
            v_sum := v_sum + i;
        END LOOP;
        DBMS_OUTPUT.PUT_LINE('Sum of first ' || p_n || ' natural numbers is: ' || v_sum);
    END;
    /
    
  2. PL/SQL Function for Sum of First n Positive Numbers:

    CREATE OR REPLACE FUNCTION SumOfNNumbers(p_n IN NUMBER) RETURN NUMBER IS
        v_sum NUMBER := 0;
    BEGIN
        FOR i IN 1..p_n LOOP
            v_sum := v_sum + i;
        END LOOP;
        RETURN v_sum;
    END;
    /
    
  3. PL/SQL Program to Find Sum of First n Natural Numbers:

    DECLARE
        v_n NUMBER := 10; -- Change this to the desired value
        v_result NUMBER;
    BEGIN
        CalculateSum(v_n);
        v_result := SumOfNNumbers(v_n);
        DBMS_OUTPUT.PUT_LINE('Sum of first ' || v_n || ' natural numbers is: ' || v_result);
    END;
    /
    

Oracle SQL Function for Finding Sum of Natural Numbers:

  1. Oracle SQL Query to Find Sum of First n Natural Numbers:

    SELECT SUM(LEVEL) AS SumOfN
    FROM dual
    CONNECT BY LEVEL <= 10; -- Change this to the desired value
    
  2. Oracle SQL Script to Calculate the Sum of First n Integers:

    DECLARE
        v_n NUMBER := 10; -- Change this to the desired value
        v_result NUMBER;
    BEGIN
        SELECT SUM(LEVEL)
        INTO v_result
        FROM dual
        CONNECT BY LEVEL <= v_n;
    
        DBMS_OUTPUT.PUT_LINE('Sum of first ' || v_n || ' natural numbers is: ' || v_result);
    END;
    /