ORA-06502 PL/SQL Numeric or Value Error: Causes and Fixes

ORA-06502 PL/SQL Numeric or Value Error: Causes and Fixes
In this article
  1. What ORA-06502 means
  2. Sample setup
  3. Case 1: character string buffer too small
  4. Case 2: bytes versus characters
  5. Case 3: number precision too large
  6. Case 4: character to number conversion error
  7. Case 5: NULL in a NOT NULL variable
  8. How to find the exact line in a big package
  9. Common mistakes
  10. Best practices to prevent ORA-06502
  11. Frequently asked questions
  12. Summary

ORA-06502: PL/SQL: numeric or value error means a PL/SQL statement tried to put a value into a variable that cannot hold it. The usual causes are a string longer than the variable's declared size, a number with more digits than its precision allows, a failed text-to-number conversion, or a NULL assigned to a NOT NULL variable. The fix is to change the declaration, the data, or the way the code handles the data.

The text after the colon tells you which case you have, and the ORA-06512 line under it tells you where. This tutorial shows each variant on a small sample table, what output to expect, and the right fix for each one, so you stop guessing and stop wrapping everything in WHEN OTHERS.

What ORA-06502 means

ORA-06502 is the error behind the predefined PL/SQL exception VALUE_ERROR (SQLCODE -6502). Oracle's error reference describes the cause as an arithmetic, numeric, string, conversion, or constraint error. Its two official examples are assigning NULL to a variable declared NOT NULL and assigning an integer larger than 99 to a variable declared NUMBER(2).

PL/SQL never silently cuts a value to fit. If the value does not fit the target, the statement fails. That is a good thing: silent truncation would corrupt your data without anyone noticing.

The error usually arrives as a small stack. Read it from the top:

ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at "APP.LOAD_CUSTOMER", line 12
ORA-06512: at line 1
A typical ORA-06502 error stack

Line one is the error and its detail text. Each ORA-06512 line is a step in the call stack. The first one points at the object and line number where the bad assignment happened. Open that line first.

Here are the detail texts you will meet most often:

Detail text after the colonWhat went wrong
character string buffer too smallA string is longer than the VARCHAR2 or CHAR variable
number precision too largeA number has more digits than NUMBER(p,s) allows
character to number conversion errorText that is not a valid number was converted to a number in PL/SQL
(no detail text)Often a NULL assigned to a NOT NULL variable or a subtype like SIMPLE_INTEGER
NULL index table key valueA NULL was used as the key of an associative array

Sample setup

Create a small customers table and a few rows. One customer has a long name and one has a phone number stored with spaces, which is exactly the kind of data that triggers ORA-06502 in real code.

CREATE TABLE customers (
  customer_id   NUMBER        PRIMARY KEY,
  customer_name VARCHAR2(60)  NOT NULL,
  city          VARCHAR2(30),
  phone         VARCHAR2(20),
  credit_limit  NUMBER(8,2)
);

INSERT INTO customers VALUES (1, 'Asha Rao', 'Pune', '9876543210', 50000);
INSERT INTO customers VALUES (2, 'Venkata Subrahmanya Lakshmi Narasimha', 'Hyderabad', '98765 43211', 125000);
INSERT INTO customers VALUES (3, 'Ravi Kumar', NULL, NULL, NULL);
COMMIT;
Sample table and data

Turn on server output in SQL*Plus or SQL Developer before running the blocks below: SET SERVEROUTPUT ON.

Case 1: character string buffer too small

This is the most common form. A VARCHAR2 variable is declared smaller than the value that lands in it.

Reproduce the error

DECLARE
  v_name VARCHAR2(20);
BEGIN
  SELECT customer_name
    INTO v_name
    FROM customers
   WHERE customer_id = 2;
  DBMS_OUTPUT.PUT_LINE(v_name);
END;
/
SELECT INTO a variable that is too small
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 4
Output (expected output)

The column can hold 60 bytes, but the variable holds only 20. Customer 1 works, so the code passes testing. Then a real customer with a long name arrives and the job fails in production.

Fix it with %TYPE

Anchor the variable to the column with %TYPE. The variable then gets the column's data type and size, and Oracle's documentation states that if the referenced declaration changes, the referencing declaration changes with it (after recompilation).

DECLARE
  v_name customers.customer_name%TYPE;
BEGIN
  SELECT customer_name
    INTO v_name
    FROM customers
   WHERE customer_id = 2;
  DBMS_OUTPUT.PUT_LINE(v_name);
END;
/
Anchor the variable to the column
Venkata Subrahmanya Lakshmi Narasimha
Output (expected output)

Use %TYPE for every variable that holds a column value. For a whole row, use customers%ROWTYPE. This removes the whole class of bug instead of fixing one variable at a time.

Concatenation that grows too big

The same error appears when you build a string in a loop, such as a comma-separated list, a CSV line or a dynamic SQL statement.

DECLARE
  v_list VARCHAR2(30);
BEGIN
  FOR r IN (SELECT customer_name FROM customers ORDER BY customer_id) LOOP
    v_list := v_list || r.customer_name || ',';
  END LOOP;
  DBMS_OUTPUT.PUT_LINE(v_list);
END;
/
The list outgrows its variable
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 5
Output (expected output)

A PL/SQL VARCHAR2 can be declared up to 32,767 bytes. If the result can never pass that, declare a bigger size. If it can, use a CLOB, which has no such limit for this kind of work.

DECLARE
  v_list CLOB;
BEGIN
  FOR r IN (SELECT customer_name FROM customers ORDER BY customer_id) LOOP
    v_list := v_list || r.customer_name || ',';
  END LOOP;
  DBMS_OUTPUT.PUT_LINE(RTRIM(v_list, ','));
END;
/
Use a CLOB when the size is open-ended
Asha Rao,Venkata Subrahmanya Lakshmi Narasimha,Ravi Kumar
Output (expected output)

Case 2: bytes versus characters

This one confuses many developers. VARCHAR2(10) usually means 10 bytes, not 10 characters, because the default length semantics is BYTE unless NLS_LENGTH_SEMANTICS is set to CHAR. In an AL32UTF8 database, an English letter takes 1 byte, but a Devanagari, Tamil or Telugu character takes 3 bytes.

DECLARE
  v_city VARCHAR2(10);       -- 10 bytes
BEGIN
  v_city := 'पुणे';           -- 4 characters, 12 bytes in AL32UTF8
  DBMS_OUTPUT.PUT_LINE(v_city);
END;
/
Four characters, but too many bytes
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 4
Output (expected output)

The string looks short, but it needs 12 bytes. Declare the length in characters instead. Oracle's PL/SQL reference recommends VARCHAR2(n CHAR) when a variable must always hold n characters in any multibyte character set.

DECLARE
  v_city VARCHAR2(10 CHAR);  -- 10 characters
BEGIN
  v_city := 'पुणे';
  DBMS_OUTPUT.PUT_LINE(v_city || ' bytes=' || LENGTHB(v_city));
END;
/
Declare the size in characters
पुणे bytes=12
Output (expected output)

LENGTH counts characters and LENGTHB counts bytes. When a string fits on screen but fails in code, compare the two. Note that the 32,767 limit is always in bytes, whichever semantics you use.

Case 3: number precision too large

A NUMBER(p,s) variable allows p total digits with s of them after the decimal point. So NUMBER(8,2) can hold up to 999999.99. A value with more digits before the decimal point fails.

DECLARE
  v_limit NUMBER(5,2);   -- max 999.99
BEGIN
  SELECT credit_limit
    INTO v_limit
    FROM customers
   WHERE customer_id = 2;
END;
/
The value has too many digits for the variable
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at line 4
Output (expected output)

Extra digits after the decimal point do not cause this error. Oracle rounds them to the scale. Assigning 123.456 to NUMBER(5,2) stores 123.46. Only digits to the left of the decimal point can overflow.

DECLARE
  v_amt NUMBER(5,2);
BEGIN
  v_amt := 123.456;
  DBMS_OUTPUT.PUT_LINE(v_amt);
END;
/
Scale is rounded, not an error
123.46
Output (expected output)

The fix is the same as for strings: anchor with customers.credit_limit%TYPE, or declare an unconstrained NUMBER for intermediate results such as totals, which often grow larger than any single column value.

Case 4: character to number conversion error

When PL/SQL converts text to a number in a procedural statement and the text is not a valid number, you get ORA-06502 with the detail character to number conversion error. Customer 2's phone number contains a space.

DECLARE
  v_phone_num NUMBER;
  v_phone     customers.phone%TYPE;
BEGIN
  SELECT phone INTO v_phone FROM customers WHERE customer_id = 2;
  v_phone_num := v_phone;     -- implicit conversion in PL/SQL
END;
/
Implicit conversion of bad text
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 6
Output (expected output)

The same bad conversion done inside a SQL statement raises a different error, ORA-01722: invalid number. So the error number tells you where the conversion happened: ORA-06502 in PL/SQL code, ORA-01722 in SQL.

Do not store phone numbers, PIN codes or account numbers in NUMBER variables. They are identifiers, not quantities, and they can contain spaces, leading zeros or a plus sign. Keep them as VARCHAR2. When you really must convert untrusted text, Oracle 12.2 and later let you handle bad values without an exception:

SELECT customer_id,
       phone,
       TO_NUMBER(phone DEFAULT NULL ON CONVERSION ERROR) AS phone_num,
       VALIDATE_CONVERSION(phone AS NUMBER)               AS is_valid
  FROM customers
 ORDER BY customer_id;
Safe conversion in Oracle 12.2 and later
CUSTOMER_IDPHONEPHONE_NUMIS_VALID
1987654321098765432101
298765 432110
31

VALIDATE_CONVERSION returns 1 when the value converts and 0 when it does not. Oracle's documentation also says it returns 1 when the input is NULL, so customer 3 counts as valid. Use it to find bad rows before a load, and use DEFAULT ... ON CONVERSION ERROR when a NULL is an acceptable result.

Case 5: NULL in a NOT NULL variable

A variable declared NOT NULL, or of a subtype with a NOT NULL constraint such as SIMPLE_INTEGER or NATURALN, raises ORA-06502 when it receives a NULL. Customer 3 has no credit limit.

DECLARE
  v_limit NUMBER NOT NULL := 0;
BEGIN
  SELECT credit_limit
    INTO v_limit
    FROM customers
   WHERE customer_id = 3;
END;
/
A NULL column value into a NOT NULL variable
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at line 4
Output (expected output)

Notice there is no detail text this time, which is a strong hint. Decide what NULL should mean for your logic and say it in the query, for example SELECT NVL(credit_limit, 0) INTO v_limit. Keep the NOT NULL on the variable if your logic truly depends on it, because it catches bad data early.

Range-constrained subtypes behave the same way. POSITIVE only accepts values of 1 or more, so assigning 0 or a negative number to it also raises ORA-06502.

How to find the exact line in a big package

In a long procedure, the line number in ORA-06512 is your best clue. But many code bases catch errors and log only SQLERRM, which hides the line. Log DBMS_UTILITY.FORMAT_ERROR_BACKTRACE as well. Oracle documents that it shows the call stack at the point where the exception was raised, even when you call it from a handler in an outer scope.

BEGIN
  DECLARE
    v_name VARCHAR2(20);
  BEGIN
    SELECT customer_name INTO v_name
      FROM customers WHERE customer_id = 2;
  END;
EXCEPTION
  WHEN VALUE_ERROR THEN
    DBMS_OUTPUT.PUT_LINE(SQLERRM);
    DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
    RAISE;
END;
/
Log the message and the line, then re-raise
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 5
Output (expected output)

The handler prints the message and the line where the error happened, then RAISE passes the error on so the caller still knows it failed. After the printed lines, your client also shows the re-raised ORA-06502. In real code, write these two values to your error log table instead of DBMS_OUTPUT.

Common mistakes

  • Hard-coding sizes. VARCHAR2(50) for a column that is later widened to 100 breaks every procedure that copied the old size. Use %TYPE.
  • Forgetting bytes versus characters. Code that works on English names fails on Hindi or Tamil names. Use VARCHAR2(n CHAR) for text from users.
  • Assuming SUBSTR fixes everything. SUBSTR(x, 1, 20) returns 20 characters, which can still be more than 20 bytes. Use SUBSTRB if the limit is in bytes, and only truncate when losing data is acceptable.
  • Numbers for identifiers. Phone numbers, PIN codes and Aadhaar-style IDs belong in VARCHAR2. Converting them to NUMBER invites conversion errors and loses leading zeros.
  • Too-small OUT parameters on the caller side. A procedure parameter declared OUT VARCHAR2 has no size of its own; it uses the caller's variable. If the caller passes a VARCHAR2(10), the procedure fails when it assigns a longer value.
  • Totals in small variables. A sum of many order amounts can exceed the precision of the column you copied. Use plain NUMBER for accumulators.
  • Mixing up ORA-06502 and ORA-12899. ORA-06502 is about a PL/SQL variable. If a value is too long for a table column on INSERT or UPDATE, you get ORA-12899: value too large for column instead.

Best practices to prevent ORA-06502

  • Declare variables with table.column%TYPE or table%ROWTYPE wherever they hold table data.
  • Use CHAR length semantics for user-facing text, either per declaration or by agreeing on NLS_LENGTH_SEMANTICS for the team. Changing the session setting affects code compiled after the change, so agree on it before you build.
  • Use CLOB for strings with no fixed upper bound, such as generated reports, JSON or dynamic SQL.
  • Validate input before converting it, with VALIDATE_CONVERSION or DEFAULT ... ON CONVERSION ERROR in 12.2 and later.
  • Log SQLERRM and DBMS_UTILITY.FORMAT_ERROR_BACKTRACE in every top-level handler, then re-raise.
  • Add test data with the longest, widest and strangest values the column allows: maximum length names, multibyte text, NULLs and large amounts.

There is no real performance cost to anchored declarations or CHAR semantics. Using CLOB for small strings does add some overhead, so keep VARCHAR2 for values that have a known, reasonable maximum.

Frequently asked questions

How do I fix ORA-06502 character string buffer too small?

Go to the line in the first ORA-06512 entry and find the variable being assigned. Make it big enough, ideally by declaring it with %TYPE, use VARCHAR2(n CHAR) if the text is multibyte, or switch to CLOB if the length has no fixed limit.

What is the difference between ORA-06502 and ORA-01722?

Both can come from a bad text-to-number conversion. ORA-01722 (invalid number) is raised when the conversion happens in a SQL statement. ORA-06502 is raised when it happens in a PL/SQL statement, such as an assignment.

Which exception catches ORA-06502 in PL/SQL?

The predefined exception VALUE_ERROR. You can write WHEN VALUE_ERROR THEN in your exception section. Catch it to log and re-raise, or to handle one known case, not to hide failures.

What is the maximum size of VARCHAR2 in PL/SQL?

32,767 bytes for a PL/SQL variable. A VARCHAR2 table column is limited to 4,000 bytes by default, or 32,767 bytes when the database uses MAX_STRING_SIZE = EXTENDED.

Why does my code work in testing but fail with ORA-06502 in production?

Production has data your test rows did not: longer names, multibyte characters, NULLs, or bigger amounts. Find the failing row by logging the key values in your exception handler, then fix the declaration rather than the single row.

Summary

  • Read the detail text after the colon to know which of the five cases you have
  • Open the line in the first ORA-06512 entry
  • Anchor variables with %TYPE and %ROWTYPE instead of hard-coded sizes
  • Use VARCHAR2(n CHAR) for multibyte text and CLOB for open-ended strings
  • Keep phone numbers and IDs as VARCHAR2 and validate before converting
  • Handle NULLs explicitly with NVL or COALESCE before NOT NULL variables
  • Log SQLERRM plus DBMS_UTILITY.FORMAT_ERROR_BACKTRACE, then re-raise
PT Ganesh

An experienced PostgreSQL DBA/SQL developer with years of expertise in designing and implementing robust database solutions. Proficient in writing complex queries, developing stored procedures, and conducting performance tuning to deliver highly efficient data-driven applications that meet business requirements.

Home
SQL
PLSQL
Interview Q&A