I have the following table:
CREATE TABLE `Foo` (
`id` int NOT NULL,
`FirstName` varchar(255) NULL,
`LastName` varchar(255) NOT NULL DEFAULT 'NONE',
PRIMARY KEY (`id`)
);
When I run the following query it take the default value of 'NONE'
:
INSERT INTO Foo (`FirstName`) VALUES('FOO');
When I run the following query:
INSERT INTO Foo (`FirstName`, `LastName`) VALUES('FOO', NULL);
it gives an error:
[Err] 1048 - Column 'LastName' cannot be null
What I want to achieve is that if a value is NULL
then MySQL should use the DEFAULT value.
Does anybody know the solution?
If a data type specification includes no explicit DEFAULT value, MySQL determines the default value as follows: If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause. If the column cannot take NULL as a value, MySQL defines the column with no explicit DEFAULT clause.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
In MySQL, 0 or NULL means false and anything else means true. The default truth value from a boolean operation is 1 .
You can set a default by using the SQL Server Management Studio (SSMS) Object Explorer or by executing Transact-SQL. If you do not assign a default value to the column, and the user leaves the column blank, then: If you set the option to allow null values, NULL will be inserted into the column.
try this
use NULL
instead of NOT NULL
CREATE TABLE `Foo` (
`id` int NOT NULL ,
`FirstName` varchar(255) NULL ,
`LastName` varchar(255) NULL DEFAULT 'NONE' ,
PRIMARY KEY (`id`)
);
and query like this
use DEFAULT
instead of NULL
INSERT INTO Foo ( `FirstName`, `LastName` ) VALUES('FOO', DEFAULT);
When you use NULL it means that you want to set NULL as a value, which can't happen for the NOT NULL column.
You can explicitly insert the default value by using DEFAULT
:
INSERT INTO Foo ( `FirstName`, `LastName` ) VALUES('FOO', DEFAULT);
Try removing NOT NULL constraint.
INSERT INTO Foo ( `FirstName`) VALUES('FOO');
When you are not inserting any value manually to lastname
you are literally inserting 'none'(default value)
into your table hence NOT NULL
constraint passes.
INSERT INTO Foo ( `FirstName`, `LastName` ) VALUES('FOO', NULL);
Here you are inserting NULL
manually to lastname
hence you are literally inserting NULL
into your table hence NOT NULL
constraint fails.
Solution:
use COALESCE()
function while inserting into table, Which will return non null parameter.
INSERT INTO Foo ( FirstName, LastName ) VALUES('FOO', COALESCE(@value, default));
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