Ошибка ora 01400 cannot insert null into

Have you gotten the “ORA-01400: cannot insert null into (string)” error? Learn what causes this and how to resolve it in this article.

ORA-01400 Cause

If you try to run an INSERT statement to insert data into a table, you may get this error.

ORA-01400: cannot insert NULL into (string)

In Oracle databases, you can store a NULL value in any column of any data type, as long as the column is not defined as “NOT NULL” or is a primary key.

A NULL value is not the same as 0 or an empty string of ”.

When you attempt to insert a record into a table, and a value of NULL is being inserted into a column that does not allow NULL values, then this error will occur.

To resolve the ORA-01400 error, you have a few options:

  1. Change your INSERT statement so it inserts a value that is not NULL
  2. Change your table definition so that it allows for NULL values.

Let’s take a look at these solutions in more detail.

Solution 1: Adjust your INSERT Statement

To avoid the ORA-01400 error, you can adjust your INSERT statement to ensure that a non-NULL value is inserted.

Let’s see an example of this.

We have a customer table here:

CREATE TABLE customer (
  customer_id NUMBER PRIMARY KEY,
  customer_name VARCHAR2(100) NOT NULL,
  email_address VARCHAR2(400)
);

The customer_id has been set as the primary key, which means it cannot take NULL values.

The customer_name field has the words NOT NULL after it. This means a NOT NULL constraint has been applied and NULL values are not allowed in this column.

The email_address column is allowed NULL values.

Now, let’s try insert a value.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (1, 'John', '[email protected]');

This value is inserted successfully.

Now, let’s try specify a NULL value for the customer_name:

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (2, NULL, '[email protected]');
SQL Error: ORA-01400: cannot insert NULL into ("INTRO_USER"."TEST_CUSTOMER"."CUSTOMER_NAME")
01400. 00000 - "cannot insert NULL into (%s)"
*Cause: An attempt was made to insert NULL into previously listed objects.
*Action: These objects cannot accept NULL values.

The error appears because a NULL value is specified for the customer_name column, which is not allowed to have NULL values.

This could also happen with this statement. We have not specified the customer_name field in the INSERT statement columns, so a NULL value is used.

INSERT INTO customer (customer_id, email_address)
VALUES (3, '[email protected]');
SQL Error: ORA-01400: cannot insert NULL into ("INTRO_USER"."TEST_CUSTOMER"."CUSTOMER_NAME")
01400. 00000 - "cannot insert NULL into (%s)"
*Cause: An attempt was made to insert NULL into previously listed objects.
*Action: These objects cannot accept NULL values.

To resolve this, we need to ensure that a value of NULL is not added into this column.

Change the value of customer_name to something that is not NULL:

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (3, 'Sarah', '[email protected]');

Or, if you’re getting data from another source, surround your value with the NVL function, which translates a NULL value to something else.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (3, NVL(input_name, 'Unknown'), '[email protected]');

If your values are coming from another system or source and definitely should not be NULL, then you might need to investigate the source of the data to find out why the values are NULL.

Solution 2: Change the Table Definition

Another way to resolve the ORA-01400 error is to change the definition of the table so that it allows for NULL values.

You can do this using the ALTER TABLE statement.

For example, to remove the NOT NULL constraint from the customer_name field in the customer table (mentioned above), you can run this command:

ALTER TABLE customer MODIFY COLUMN customer_name VARCHAR2(100);

This will remove the NOT NULL constraint from the table.

Now, you can insert a NULL value into this column.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (4, NULL, '[email protected]');

Conclusion

So, that’s how you can resolve the ORA-01400 error.

It’s caused by inserting a NULL value into a column that cannot be NULL.

You can resolve it by adjusting your INSERT statement or modifying your table.

I’m trying to insert a record into a table, but getting the error —

‘ORA-01400: cannot insert NULL into (….’. The table structure is:

I migrate from Mysql to Oracle.

On Mysql this works, but on Oracle it is not working. How can I fix this? Do I need write all column insert query or unselect not null option

  • mysql
  • oracle
  • migration
  • notnull
  • ora-01400

asked Mar 6, 2013 at 12:25

neoerol's user avatar

neoerolneoerol

9311 gold badge12 silver badges18 bronze badges

9

  • MySQL lets you insert null into not-null columns (and silently converts that to something else). Oracle actually obeys your constraint that you do not want to store NULLs in that columns. The solution is to provide a value instead of NULL when inserting.

    – user330315

    Mar 6, 2013 at 12:28

  • there’s a NOT NULL constraint on certain column(s), so you need to either provide a value during insert, or perhaps a trigger is missing (which can populate a column from a sequence for example)

    Mar 6, 2013 at 12:28

  • Ok. How can i drop ‘not null’ option on Oracle all tables?

    Mar 6, 2013 at 12:34

  • You can write a script using data from all_tab_cols altering columns to be nullable, but are you sure you want that ? why not use NVL ?

    Mar 6, 2013 at 12:39

  • @a_horse_with_no_name, does it let you insert nulls always, or is it only the way it works with empty strings as here which is not like in oracle here

    Mar 6, 2013 at 12:49

1 Answer

Try this:

create or replace trigger EDITIONS_COR
  before insert or update on EDITIONS
  for each row
begin
  if INSERTING then
    select EDITIONS_SEQ.nextval into :new.ID from DUAL;
  end if;
  :new.CORDATE:=SYSDATE;
  :new.USERNAME:=USER;
end;

ChrisF's user avatar

ChrisF

135k31 gold badges255 silver badges325 bronze badges

answered Apr 17, 2014 at 17:07

user3546225's user avatar

ORA-01400 means that there’s a column which was found as NOT NULL is not listed in the INSERT statement, you have to provide a value for it. For example, I tried to insert a row into a table.

SQL> conn hr/hr
Connected.
SQL> insert into hr.countries (country_id, country_name) values ('SE', 'Sweden');
insert into hr.countries (country_id, country_name) values ('SE', 'Sweden')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("HR"."COUNTRIES"."REGION_ID")

Let’s describe the table’s definition.

SQL> desc hr.countries;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COUNTRY_ID                                NOT NULL CHAR(2)
 COUNTRY_NAME                              NOT NULL VARCHAR2(40)
 REGION_ID                                 NOT NULL NUMBER

As you can see, the column is NOT NULL which is one type of constraints to keep data integrity.

Please note that, not only in a normal INSERT, but also in import, SQL*Loader, GoldenGate, Hibernate and Informatica could see ORA-01400 sometimes. Especially for data import which includes imp of original import and impdp of data pump.

As for JDBC exception handling, sometimes the error message may not be so obvious because it’s related to constraint violation signals, but fortunately the error stack that companies with ORA-01400 is mostly the same:

  • java.sql.SQLException
  • java.sql.SQLNonTransientException
  • java.sql.SQLIntegrityConstraintViolationException

Solutions to ORA-01400

Now, we can have 3 choices to solve ORA-01400.

  1. Put the Column on the List of INSERT
  2. Remove NOT NULL constraint from the Column
  3. Provide a default Value for the Column

Put the Column on the List of INSERT

You have to modify the statement and provide a proper value to it at run-time.

SQL> insert into hr.countries (country_id, country_name, region_id) values ('SE', 'Sweden', 1);

1 row created.

It’s successful. Now we have to revert the operation for later steps.

SQL> rollback;

Rollback complete.

I know, sometimes, you don’t have any proper value of this column. So you can go for the next choice.

Remove NOT NULL constraint from the Column

You can either disable the constraint or drop it, but the drawback is that you have to change the definition of the table, the data integrity may be compromised.

Disable the constraint

Let’s check which constraint should be disabled from the column.

SQL> column constraint_name format a25;
SQL> select a.constraint_name, b.status from user_cons_columns a inner join user_constraints b on a.constraint_name = b.constraint_name where a.table_name = 'COUNTRIES' and a.column_name = 'REGION_ID' and b.constraint_type = 'C' and search_condition_vc like '%NOT NULL';

CONSTRAINT_NAME           STATUS
------------------------- --------
SYS_C007819               ENABLED

Then we disable the constraint by ALTER TABLE DISABLE CONSTRAINT.

SQL> alter table countries disable constraint SYS_C007819;

Table altered.

Check the status again.

SQL> select a.constraint_name, b.status from user_cons_columns a inner join user_constraints b on a.constraint_name = b.constraint_name where a.table_name = 'COUNTRIES' and a.column_name = 'REGION_ID' and b.constraint_type = 'C' and search_condition_vc like '%NOT NULL';

CONSTRAINT_NAME           STATUS
------------------------- --------
SYS_C007819               DISABLED

SQL> desc countries;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COUNTRY_ID                                NOT NULL CHAR(2)
 COUNTRY_NAME                              NOT NULL VARCHAR2(40)
 REGION_ID                                          NUMBER

As you can see, the constraint was removed, OK, just temporarily.

Drop the constraint

To remove the constraint permanently, you can drop it by ALTER TABLE DROP CONSTRAINT.

SQL> alter table countries drop constraint SYS_C007819;

Table altered.

SQL> select a.constraint_name, b.status from user_cons_columns a inner join user_constraints b on a.constraint_name = b.constraint_name where a.table_name = 'COUNTRIES' and a.column_name = 'REGION_ID' and b.constraint_type = 'C';

no rows selected

Dropping a NOT NULL constraint can be easier than the above statement. I guess you’d like to know more ways to add or drop a NOT NULL constraint.

No matter you disable or drop it, you can insert the row now.

SQL> insert into hr.countries (country_id, country_name) values ('SE', 'Sweden');

1 row created.

It’s successful. Now we have to revert the operation for later steps.

SQL> rollback;

Rollback complete.

SQL> alter table countries modify (region_id not null);

Table altered.

Provide a default Value for the Column

This could be the best solution to ORA-01400.

SQL> alter table hr.countries modify (region_id default 1);

Table altered.

SQL> insert into hr.countries (country_id, country_name) values ('SE', 'Sweden');

1 row created.

The best thing is that you don’t have to modify INSERT statements or remove NOT NULL constraints from the column. The business logic stays stable.

ORA-01400

ORA-01400: обязательная (NOT NULL) колонка пропущена, или произошел NULL во время вставки

Причина:

Когда вы вставляете или изменяете строки, вы не указываете значение для колонки определенной как NOT NULL.

Действие:

Укажите значение для каждой колонки NOT NULL, или измените определение таблицы разрешающее нулевые значения в колонках, которые сейчас определены как NOT NULL.

I’m trying to insert data in a backup table with help of rowtype as below

   declare
        vl_bkp_rec schema.table1%ROWTYPE; 
        BEGIN   
        FOR cur_rec IN
              (SELECT      *
              FROM schema.table1
              WHERE column_1        ='3f1d6348-014e-1000-8461-700c000493e0'
              AND primary_key_column NOT IN ('8dc81f6e-0156-1000-8291-700e000493e0')
              )
              LOOP
                INSERT INTO schema.backup_table VALUES vl_bkp_rec;
         END LOOP; 
COMMIT;
        EXCEPTION
        WHEN OTHERS THEN
          lv_err_msg := SUBSTR(SQLERRM, 1, 2999);
          DBMS_OUTPUT.PUT_LINE('Handled - error while executing script. =>'|| lv_err_msg );
          ROLLBACK;
        END;
        /

i’m getting below error

Handled - error while executing script. =>ORA-01400: cannot insert NULL into ("schema"."backup_table"."primary_key_column")

but table1 and backup_table have exactly same structure. (created backup_table as below)

CREATE TABLE schema.backup_table AS
  (SELECT * FROM schema.table1 WHERE rownum <1
  ); 

and select query used above fetches valid data. What am I doing wrong here?

kam1l's user avatar

kam1l

731 silver badge5 bronze badges

asked Sep 2, 2016 at 12:11

Onkar B's user avatar

2

You need to use your variable in the below way. Currently in your code the variable declared as table type is not getting filled: See below how to use it.

  declare
     vl_bkp_rec table1%ROWTYPE; 
     BEGIN   
        FOR cur_rec IN
                  (SELECT      * 
                     FROM table1             
                  )
        LOOP                                
            vl_bkp_rec:=cur_rec; --Assign values of the cursor variable to your variable

            INSERT INTO  backup_table VALUES vl_bkp_rec;

        END LOOP; 
    COMMIT;
       EXCEPTION
       WHEN OTHERS THEN
         --lv_err_msg := SUBSTR(SQLERRM, 1, 2999); ---you need to decalre it befor using it
         DBMS_OUTPUT.PUT_LINE('Handled - error while executing script. =>' );
         ROLLBACK;
       END;
       /

answered Sep 2, 2016 at 13:08

XING's user avatar

XINGXING

9,6184 gold badges22 silver badges38 bronze badges

1

Понравилась статья? Поделить с друзьями:
  • Ошибка ora 04091
  • Ошибка kbdru dll
  • Ошибка launcher exe bad image
  • Ошибка ora 01033 oracle
  • Ошибка erp 23 voice