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));
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);
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.
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.
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.
INSERT INTO foo (id, message)
VALUES
(i_id, IFNULL(i_message,DEFAULT(message)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With