Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert default into not null column if value is null

Tags:

mysql

I have a table foo, which has a NOT NULL column with a default called message:

CREATE TABLE foo(
    id int PRIMARY KEY,
    message varchar(64) NOT NULL DEFAULT 'Hello'
)

There is a stored procedure bar that inserts into foo:

CREATE PROCEDURE bar(
    i_id int,
    i_message varchar(64)
)
BEGIN

    -- other logic

    IF i_message IS NOT NULL THEN
        INSERT INTO foo (id, message) VALUES (i_id, i_message);
    ELSE
        INSERT INTO foo (id, message) VALUES (i_id, DEFAULT);
        -- could also be: INSERT INTO foo (id) VALUES (i_id);
    END IF;
 END;

You can see, I have to conditionally branch in order for my insert to use the default if i_message is null. That's fine for just one column, but consider if foo had many more NOT NULL DEFAULT columns - the syntax would be way to unwieldy.

Is there a syntax I can use to specify that an inserted value should fall back to the default if null? I tried the following but understandably got syntax errors:

INSERT INTO foo (id, message) VALUES (i_id, COALESCE(i_message, DEFAULT));
INSERT INTO foo (id, message) VALUES (i_id, IFNULL(i_message, DEFAULT));
like image 896
Paul Bellora Avatar asked Dec 13 '12 20:12

Paul Bellora


People also ask

How do I insert a NULL value into a NOT NULL column?

Code Inspection: Insert NULL into NOT NULL columnCREATE TABLE br2 ( id INT NOT NULL, col1 NVARCHAR (20) NOT NULL, col2 NVARCHAR (20) NOT NULL, ); -- INSERT INTO br2 (id, col1, col2) VALUES (1, NULL, NULL);

Can we use default with not null?

Yes, adding a column with NOT NULL and a default doesn't actually write the values to all the rows at the time of the alter, so it is no longer a size-of-data operation. When you select from the table, the columns are actually materialized from sys.

Can we use NOT NULL and default in SQL?

By default, a column holds NULL values. In the example, we use the NOT NULL constraint that enforces a column not to accept NULL values. If we prohibit to use NULL values, we must set the DEFAULT value that SQL can use when we create a new record.

Can a column defined as a NOT NULL can have a default value of NULL?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.


1 Answers

  INSERT INTO foo (id, message) 
  VALUES
  (i_id, IFNULL(i_message,DEFAULT(message)));
like image 170
Wrikken Avatar answered Sep 25 '22 09:09

Wrikken