Psycopg2.errors.numericvalueoutofrange: integer out of range

The error message “psycopg2.errors.numericvalueoutofrange: integer out of range” occurs when you try to insert or update a value that is outside the valid range for an integer data type in the PostgreSQL database. This error typically happens when the value you are trying to insert or update is greater or smaller than the maximum or minimum value allowed for an integer.

Here’s an example to illustrate the error:


import psycopg2

# Connect to the PostgreSQL database
conn = psycopg2.connect(host="your_host", port="your_port", database="your_database", user="your_user", password="your_password")

# Create a cursor object
cursor = conn.cursor()

# Try to insert an out-of-range integer value into a column
try:
    cursor.execute("INSERT INTO your_table (your_column) VALUES (1000000000000000000000)")
    conn.commit()
except psycopg2.errors.NumericValueOutOfRange as e:
    print("Error:", e)

# Close the cursor and connection
cursor.close()
conn.close()
  

In the above example, we are trying to insert the value 1000000000000000000000 into the column “your_column”, which is an integer column. Since the value is outside the valid range for an integer, the psycopg2 library raises the “psycopg2.errors.numericvalueoutofrange” error.

To resolve this error, you can either adjust the value you are trying to insert so that it falls within the valid range for an integer, or you can change the data type of the column to accommodate larger values, such as using a bigint or numeric data type instead of integer.

Leave a comment