Search code examples
oracledefaultnotnull

Insert default value when null is inserted


I have an Oracle database, and a table with several not null columns, all with default values.

I would like to use one insert statement for any data I want to insert, and don't bother to check if the values inserted are nulls or not.

Is there any way to fall back to default column value when null is inserted?

I have this code:

<?php
if (!empty($values['not_null_column_with_default_value'])) {
    $insert = "
        INSERT INTO schema.my_table
            ( pk_column, other_column, not_null_column_with_default_value)
        VALUES
            (:pk_column,:other_column,:not_null_column_with_default_value)
     ";
} else {
    $insert = "
        INSERT INTO schema.my_table
            ( pk_column, other_column)
        VALUES
            (:pk_column,:other_column)
     ";        
}

So, I have to omit the column entirely, or I will have the error "trying insert null to not null column". Of course I have multiple nullable columns, so the code create insert statement is very unreadable, ugly, and I just don't like it that way.

I would like to have one statement, something similar to:

INSERT INTO schema.my_table
    ( pk_column, other_column, not_null_column_with_default_value)
VALUES
    (:pk_column,:other_column, NVL(:not_null_column_with_default_value, DEFAULT) );

That of course is a hypothetical query. Do you know any way I would achieve that goal with Oracle DBMS?

EDIT:

Thank you all for your answers. It seams that there is no "standard" way to achieve what I wanted to, so I accepted the IMO best answer: That I should stop being to smart and stick to just omitting the null values via automatically built statements.

Not exactly what I would like to see, but no better choice.


Solution

  • For those who reading it now:

    In Oracle 12c there is new feature: DEFAULT ON NULL. For example:

    CREATE TABLE tab1 (
      col1        NUMBER DEFAULT 5,
      col2        NUMBER DEFAULT ON NULL 7,
      description VARCHAR2(30)
    );
    

    So when you try to INSERT null in col2, this will automatically be 7.