The NOT NULL constraint prevents NULL values from being inserted into a column.
Oracle provides two ways to define constraint names: system-generated or user-defined.
CREATE TABLE table_not_null_1
(
id1 NUMBER(1,0) NOT NULL -- the NOT NULL constraint name will be generated automatically by Oracle as "SYS_C007034"
, id2 NUMBER(1,0) CONSTRAINT cc_table_not_null_1_id2 NOT NULL -- the NOT NULL constraint name is explicitly defined as "CC_TABLE_NOT_NULL_1_ID2"
);
-
Check the creation of the constraint:
SELECT constraint_name, constraint_type, generated, search_condition
FROM user_constraints
WHERE table_name = 'TABLE_NOT_NULL_1';
Query result:
+-------------------------+-----------------+----------------+-------------------+
| CONSTRAINT_NAME | CONSTRAINT_TYPE | GENERATED | SEARCH_CONDITION |
+-------------------------+-----------------+----------------+-------------------+
| SYS_C007034 | C | GENERATED NAME | "ID1" IS NOT NULL |
+-------------------------+-----------------+----------------+-------------------+
| CC_TABLE_NOT_NULL_1_ID2 | C | USER NAME | "ID2" IS NOT NULL |
+-------------------------+-----------------+----------------+-------------------+
Note: CONSTRAINT_TYPE 'C' indicates a CHECK constraint, which is how Oracle internally implements NOT NULL constraints.
-
Check the nullability of the table columns:
SELECT column_name, CASE WHEN nullable = 'N' THEN 'NO' ELSE 'YES' END AS nullable
FROM user_tab_columns
WHERE table_name = 'TABLE_NOT_NULL_1';
Query result:
+-------------+----------+
| COLUMN_NAME | NULLABLE |
+-------------+----------+
| ID1 | NO |
+-------------+----------+
| ID2 | NO |
+-------------+----------+
The NULLABLE column in USER_TAB_COLUMNS shows 'N' for columns with NOT NULL constraints.
-
Insert NULL values into the table:
INSERT INTO table_not_null_1(id1, id2) VALUES(NULL, 1);
INSERT INTO table_not_null_1(id1, id2) VALUES(1, NULL);
Query result:
Error starting at line 1 in command:
INSERT INTO TABLE_NOT_NULL_1(ID1, ID2) VALUES(NULL, 1)
Error report: ORA-01400: cannot insert NULL into ("HR"."TABLE_NOT_NULL_1"."ID1")
*Cause: A NULL value was inserted into a column defined as NOT NULL.
*Action: Do not insert NULLs or modify the column definition.
Error starting at line 2 in command:
INSERT INTO TABLE_NOT_NULL_1(ID1, ID2) VALUES(1, NULL)
Error report: ORA-01400: cannot insert NULL into ("HR"."TABLE_NOT_NULL_1"."ID2")
*Cause: A NULL value was inserted into a column defined as NOT NULL.
*Action: Do not insert NULLs or modify the column definition.
Oracle returns ORA-01400 error when attempting to insert NULL values into NOT NULL columns.