I faced a problem when inserting a NULL value into a column defined as NOT NULL WITH DEFAULT values.
In this example, I removed most of the columns for illustration purposes.
CREATE TABLE
FKTIM04
(
OBJECTID CHARACTER(32) NOT NULL,
UP_CHANGE_CL CHARACTER(1) DEFAULT '1' NOT NULL,
UP_CTRL_CL CHARACTER(1) DEFAULT '0' NOT NULL,
CONSTRAINT PK_FKTIM04 PRIMARY KEY (OBJECTID)
);
When I execute this SQL statement, there is an error:
INSERT INTO KTI.FKTIM04 (
UP_Change_CL
,UP_ctrl_CL
,ObjectID
)
VALUES (
NULL
,NULL
,'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
Error:
[Code: -407, SQL State: 23502] Assignment of a NULL value to a NOT
NULL column "TBSPACEID=2, TABLEID=1298, COLNO=46" is not allowed..
SQLCODE=-407, SQLSTATE=23502, DRIVER=4.22.29
I know that the column is defined as NOT NULL. If it tries to insert a NULL into the column, shouldn't it take the DEFAULT value instead?
Please teach me how to get the DEFAULT values to be inserted instead.
What should I look out for?
Thank you.
The default value will be used for a column if a value is not supplied in the INSERT statement for this column.
So don't include the columns that you want to get their default values in the list like this:
INSERT INTO KTI.FKTIM04 (
ObjectID
)
VALUES (
'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
this way the row will be inserted and the 2 columns, since they were not specified in the list, will get their default values.
See the demo.
Another way to achieve the same is by using DEFAULT keyword:
INSERT INTO FKTIM04 (
UP_Change_CL
,UP_ctrl_CL
,ObjectID
)
VALUES (
DEFAULT
,DEFAULT
,'UMSTM0LW8A8Z50DT4WA7U93EEQDRXRTH'
)
See the demo.
Related
I'm new to SQL Server and I am getting this error "Cannot insert the value NULL into column 'Occupied', table 'DBProjectHamlet.dbo.tblGrave'; column does not allow nulls. INSERT fails. The statement has been terminated."
This is my code for the insert followed by the code to create the table
INSERT INTO tblGrave (GraveName)
SELECT Grave
FROM tblPlotsandOccupants
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tblGrave' AND TABLE_SCHEMA = 'dbo')
DROP TABLE dbo.tblGrave;
GO
CREATE TABLE tblGrave
(
GraveID INT IDENTITY (1,1),
GraveName VARCHAR(MAX) NULL,
GraveTypeID INT NOT NULL,
PlotID INT NOT NULL,
Occupied BIT NOT NULL
)
I'm not trying to insert anything into column Occupied, I don't know why this is happening or how to fix it. I just want to insert values into tblGrave (GraveName). Any help would be great.
Exactly! You aren't doing anything with Occupied and that is the problem. The column is specified to be NOT NULL but has no default value. You are not inserting a value, so it gets the default. The default default is NULL, and that is not allowed.
One simple solution is:
INSERT INTO tblGrave (GraveName, Occupied)
SELECT Grave, 0
FROM tblPlotsandOccupants;
This fixes your immediate problem, but will then you will get an error on PlotId.
A more robust solution would add a default value for the NOT NULL columns and declare the rest to be nullable (the default). Something like this:
CREATE TABLE tblGrave (
GraveID INT IDENTITY (1,1) PRIMARY KEY,
GraveName VARCHAR(MAX),
GraveTypeID,
PlotID INT,
Occupied BIT NOT NULL DEFAULT 0
);
When you created your table, you defined that column as "NOT NULL" rather than allowing it to be null.
You need to either allow "Occupied" to be null, set a default value, or define the value that you want upon inserting.
You can even set the value to be ' ' which is blank but isn't null.
EDIT
Note #Gordon's answer for sql examples.
These is my example table definition:
CREATE TABLE [MyTable]
(
[ColumnName] [bit] NOT NULL
)
ALTER TABLE [MyTable] ADD DEFAULT ((0)) FOR [ColumnName]
I want to be able to pass a Null value to my stored procedure's #ColumnValue, something like:
#ColumnValue = null;
INSERT INTO [MyTable] ([ColumnName])
VALUES (#ColumnValue)
But I'm getting this error:
"Cannot insert the value NULL into column... INSERT fails with"
Why the DEFAULT constraints not working?
Solved:
as #J.D. Pace said: The default value will be inserted only if the value is not specified on the Insert statement.
so as #dotNET suggested, i have specified the default value in the INSERT query statement using the ISNULL:
ISNULL - The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:
#ColumnValue = null;
INSERT INTO [MyTable] (
[ColumnName]
)
VALUES (
ISNULL(#ColumnValue, 0)
)
A table with only one column of bit type with a default value seems to be a bad design. This stuff can almost certainly be stored in a different and better way. On the other hand, if there are other columns in the table that you didn't include in the post, just skip this particular column in your INSERT query and it will work fine. Lastly, you can specify the default value in your INSERT query too.
I have a table that holds log lines, and added some computed columns:
CREATE TABLE IF NOT EXISTS log_lines (
id identity NOT NULL PRIMARY KEY,
time_stamp bigint NOT NULL,
-- some other columns here ...
type_text varchar NOT NULL,
flag_text varchar NOT NULL,
-- computed columns
shield boolean NOT NULL AS type_text LIKE '%Shield%',
-- some other computed columns here ...
-- all BOOLEAN columns computed from values of the VARCHAR columns
);
When i try to insert a row into this table:
INSERT
INTO log_lines ( time_stamp, ... , type_text, flag_text )
VALUES ( 123456789, ... , '', '' )
H2 throws a weird error
org.h2.jdbc.JdbcSQLException: Column "SHIELD" must be in the GROUP BY list; SQL statement:
INSERT
INTO LOG_LINES ( TIME_STAMP, ... , TYPE_TEXT, FLAG_TEXT )
VALUES ( 123456789, ... , '', '' ) [90016-182]
I am really lost here...
EDIT
Just after posting the question i found the solution to why was an error thrown.
The culprit was another computed column, that was declared before shield and was computed from it. Moved that computed column to the end of the CREATE TABLE statement, and it is working just fine.
But the question of "What does the error mean?" remains...
I have a sql table and here is my column which gives error. When I try to add a new record which has null active_status to this table, It gives "not-null property references a null or transient value" error. Is there any idea?
active_status character varying(30) NOT NULL DEFAULT 'NEW'::character varying,
EDIT: I have created a new simple table;
CREATE TABLE mytable
(
"MyData" character varying(30) NOT NULL DEFAULT 'NEW'::character varying,
CONSTRAINT mytable_pkey PRIMARY KEY ("MyData" )
)
WITH (
OIDS=FALSE
);
ALTER TABLE mytable
OWNER TO postgres;
When I try to insert a string, it runs fine;
insert into mytable values('ssss');
But when I try to insert a null value it gives error;
insert into mytable values(null);
ERROR: null value in column "MyData" violates not-null constraint
SQL state: 23502
With this statement:
insert into mytable values(null);
you explicitely requested to insert a NULL value into the column MyData and therefor you get the error message.
If you want to use the default value, you need to tell the DBMS to do so:
insert into mytable values (default);
Btw: it is much better coding style to always specify the columns in the insert statement:
insert into mytable ("MyData") values (null);
And another thing: you should avoid using quoted identifiers ("MyData" vs. MyData) , they simply are more trouble than it's worth it.
You need to first create the column with NULL constraint. Update all rows for that column with the default values. Alter the column to have Not Null constraint
I've seen many times the following syntax which defines a column in a create/alter DDL statement:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) NOT NULL DEFAULT "MyDefault"
The question is: since a default value is specified, is it necessary to also specify that the column should not accept NULLs? In other words, doesn't DEFAULT render NOT NULL redundant?
DEFAULT is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT in UPDATE statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL constraint will cause an error with statements 4, 6, while 1-3, 5 are still valid statements. So to answer your question: No, they're not redundant.
Even with a default value, you can always override the column data with null.
The NOT NULL restriction won't let you update that row after it was created with null value
My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.
Like this:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL
I would say not.
If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.
With not null set, then you can't insert a null value into the field as it'll throw an error.
Think of it as a fail safe mechanism to prevent nulls.
In other words, doesn't DEFAULT render NOT NULL redundant ?
No, it is not redundant. To extended accepted answer. For column col which is nullable awe can insert NULL even when DEFAULT is defined:
CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);
-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);
+-----+------+
| ID | COL |
+-----+------+
| 1 | null |
+-----+------+
Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL:
CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL);
INSERT INTO t2(id, col) VALUES(1, NULL);
+-----+-----+
| ID | COL |
+-----+-----+
| 1 | 10 |
+-----+-----+
Here we tried to insert NULL but get default instead.
db<>fiddle demo
ON NULL
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.
In case of Oracle since 12c you have DEFAULT ON NULL which implies a NOT NULL constraint.
ALTER TABLE tbl ADD (col VARCHAR(20) DEFAULT ON NULL 'MyDefault');
ALTER TABLE
ON NULL
If you specify the ON NULL clause, then Oracle Database assigns the
DEFAULT column value when a subsequent INSERT statement attempts to
assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE
constraint state are implicitly specified. If you specify an inline
constraint that conflicts with NOT NULL and NOT DEFERRABLE, then an
error is raised.