Sub topic 4
Requiring values with NOT NULL
This chapter assumes you can write basic SELECT, INSERT, UPDATE and DELETE statements. It also assumes you have run a simple CREATE TABLE and can connect to an Oracle Database 12c or later schema. You do not need to know the other constraint types yet. They have their own chapters.
A NOT NULL constraint stops a column from holding NULL. NULL means "no value is known or applicable." It is not zero and not an empty string. This chapter covers how to declare the constraint, how Oracle treats it differently from the other constraint types, how it interacts with defaults and identity columns, and which errors you will see.
What NOT NULL does
Every column accepts NULL unless you say otherwise. Add NOT NULL when a row is meaningless or unsafe without a value in that column. Examples are an employee's email address or a hire date.
The constraint is checked on every INSERT and UPDATE. If a statement would leave a NOT NULL column empty, Oracle rejects the whole statement. Rows the statement had already processed are rolled back with it. Earlier statements in your transaction stay as they were.
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);
INSERT INTO departments (department_name) VALUES (NULL);The INSERT fails with ORA-01400: cannot insert NULL into ("YOURSCHEMA"."DEPARTMENTS"."DEPARTMENT_NAME"). The message names the schema, table and column, but not a constraint. This is the first difference from other constraint types, covered below.
Declaring NOT NULL
NOT NULL can be written in two ways: as an inline column property, or with a name.
Inline and unnamed
The short form puts the keywords after the data type, as in department_name VARCHAR2(100) NOT NULL. Oracle creates a constraint and gives it a generated name such as SYS_C0012345. Generated names are hard to read in the data dictionary and change when you recreate the table in another environment.
Inline and named
You can name the constraint by putting CONSTRAINT name before NOT NULL:
CREATE TABLE projects (
project_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
project_name VARCHAR2(100) CONSTRAINT projects_name_nn NOT NULL,
start_date DATE CONSTRAINT projects_start_nn NOT NULL
);Naming helps when you later need to find, disable or drop the constraint. The suffix _nn is a common convention. Pick one pattern and apply it to every table.
Why there is no out-of-line form in CREATE TABLE
The other constraint types can be declared out of line, as separate entries after the column list. NOT NULL cannot. This statement is invalid:
-- Invalid: NOT NULL is not allowed as a table constraint.
CREATE TABLE bad_example (
name VARCHAR2(50),
CONSTRAINT bad_example_nn NOT NULL (name)
);You can get the same effect with a CHECK (name IS NOT NULL) constraint, but Oracle then treats it as a check constraint and not as a NOT NULL constraint. The difference is covered in the next section.
NOT NULL is a column-level rule
Oracle stores NOT NULL as a property of one column, even though it also appears in USER_CONSTRAINTS. That has several practical effects:
- It applies to exactly one column. You cannot write one
NOT NULLover several columns. - In the data dictionary it appears with
constraint_type = 'C', the same code used forCHECKconstraints. To tell them apart, look atsearch_condition, which holds text like"DEPARTMENT_NAME" IS NOT NULL. DESCRIBE(SQL*Plus and SQLcl) showsNOT NULLin theNull?column. This is the quickest way to check a column.- A
CHECK (col IS NOT NULL)constraint is not shown byDESCRIBEasNOT NULL. Tools that read the column's nullability, including some ORMs and design tools, also miss it.
Interaction with defaults
A default fills in a value when the column is left out of an INSERT. It does not protect against an explicit NULL. This surprises many developers.
CREATE TABLE tasks (
task_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR2(100) NOT NULL,
status VARCHAR2(10) DEFAULT 'OPEN'
);
-- status is omitted, so the default applies: 'OPEN'
INSERT INTO tasks (title) VALUES ('Write report');
-- status is explicitly NULL, so the default is NOT used: stored as NULL
INSERT INTO tasks (title, status) VALUES ('Review report', NULL);The second row stores NULL in status, because nothing forbids it. Adding NOT NULL to the column would make the second statement fail instead of storing a hidden gap.
Oracle also lets you write DEFAULT ON NULL, which replaces an explicit NULL with the default. In this form, the column is implicitly NOT NULL:
CREATE TABLE tasks_v2 (
task_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR2(100) NOT NULL,
status VARCHAR2(10) DEFAULT ON NULL 'OPEN'
);
INSERT INTO tasks_v2 (title, status) VALUES ('Review report', NULL);
-- status is stored as 'OPEN'Use plain DEFAULT 'OPEN' NOT NULL when you want a missing value filled in but an explicit NULL rejected. Use DEFAULT ON NULL when callers, such as an application that always binds every column, may pass NULL and you want the default instead of an error.
| Declaration | Column omitted | Explicit NULL supplied |
|---|---|---|
| `DEFAULT 'OPEN'` | `'OPEN'` stored | `NULL` stored |
| `DEFAULT 'OPEN' NOT NULL` | `'OPEN'` stored | Error ORA-01400 |
| `DEFAULT ON NULL 'OPEN'` | `'OPEN'` stored | `'OPEN'` stored |
NOT NULL with keys and identity columns
A primary key column is always NOT NULL. If you declare PRIMARY KEY on a column, Oracle makes the column mandatory automatically. You do not need to write NOT NULL as well, although it does no harm. This is why department_id above has no explicit NOT NULL.
Identity columns follow the same logic. GENERATED ALWAYS AS IDENTITY and GENERATED BY DEFAULT ON NULL AS IDENTITY never leave the column empty, because Oracle produces a value. With GENERATED BY DEFAULT ON NULL, Oracle also marks the column NOT NULL. A later chapter covers the generation modes in detail.
A unique constraint is different. It allows NULL in its columns unless you add NOT NULL. If a column should be both unique and required, use both constraints.
The empty-string trap
Oracle treats an empty string of VARCHAR2 type as NULL. This makes NOT NULL stricter than it looks on a character column.
INSERT INTO departments (department_name) VALUES ('');This fails with ORA-01400 as well, because '' is converted to NULL. A value consisting only of spaces, such as ' ', is not NULL and passes. If blank names are a problem, add a CHECK constraint such as CHECK (TRIM(department_name) IS NOT NULL). The CHECK chapter covers this kind of rule.
Adding NOT NULL to an existing table
Use ALTER TABLE ... MODIFY to change nullability. The syntax differs from adding other constraints, which use ADD CONSTRAINT.
-- Make an existing column mandatory (generated constraint name)
ALTER TABLE employees MODIFY (email NOT NULL);
-- Same, with an explicit name
ALTER TABLE employees MODIFY (email CONSTRAINT employees_email_nn NOT NULL);
-- Make the column optional again
ALTER TABLE employees MODIFY (email NULL);Existing rows must comply
Oracle checks the existing data when you add the constraint. If any row already holds NULL in that column, the statement fails with ORA-02296: cannot enable (SCHEMA.) - null values found. Find and fix the offending rows first:
SELECT employee_id FROM employees WHERE email IS NULL;
UPDATE employees
SET email = 'unknown-' || employee_id || '@example.com'
WHERE email IS NULL;
ALTER TABLE employees MODIFY (email CONSTRAINT employees_email_nn NOT NULL);Adding a constraint to a large table takes a lock while Oracle validates every row, so plan it for a quiet period. A related shortcut is NOVALIDATE, which adds the constraint without checking old rows. It is covered in the chapter on constraint states.
Adding a NOT NULL column with a default
You can add a new mandatory column and give it a default in one step:
ALTER TABLE employees ADD (country_code VARCHAR2(2) DEFAULT 'US' NOT NULL);Existing rows receive the default, so the constraint is satisfied. In Oracle Database 11g and later, this operation is a metadata-only change for most tables, so it stays fast even on large tables. Without the DEFAULT, adding a NOT NULL column to a table with rows fails, since the new column would be empty in every existing row.
Finding NOT NULL constraints
You can list them with the data dictionary, or read nullability per column.
SELECT constraint_name, search_condition_vc
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
AND constraint_type = 'C';
SELECT column_name, nullable
FROM user_tab_columns
WHERE table_name = 'EMPLOYEES'
ORDER BY column_id;The nullable column holds 'N' for mandatory columns and 'Y' for optional ones. In Oracle Database 12.2 and later, USER_CONSTRAINTS offers the search_condition_vc column, which holds the condition as text. In older releases, the search_condition column is a LONG that you cannot filter with WHERE.
Common errors
| Error | When it appears | Typical fix |
|---|---|---|
| ORA-01400 | `INSERT` leaves a `NOT NULL` column empty | Supply a value, or add a default |
| ORA-01407 | `UPDATE` sets a `NOT NULL` column to `NULL` | Remove the `NULL` assignment |
| ORA-02296 | Adding `NOT NULL` when `NULL` rows exist | Update the rows first |
| ORA-01758 | Adding a `NOT NULL` column without a default to a populated table | Add a `DEFAULT`, or add the column as nullable, fill it, then modify it |
| ORA-01451 | `MODIFY ... NULL` on a column that is already nullable | Remove the redundant statement |
Design guidance
- Make a column
NOT NULLwhen the business rule says a row cannot exist without it. Do not use it only to avoid handlingNULLin queries. - Prefer a real default plus
NOT NULLoverNULLfor flags and statuses, becauseNULLforces three-valued logic inWHEREclauses. - Do not use placeholder values such as
'N/A'or-1in place ofNULLfor genuinely unknown data. They break sums, averages and uniqueness. - Remember the empty-string rule when you load data from files or applications that produce
''.
Exercise
A table has the column status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL. What happens for each statement: (a) INSERT INTO t (id) VALUES (1), (b) INSERT INTO t (id, status) VALUES (2, NULL), (c) INSERT INTO t (id, status) VALUES (3, '')? Then explain what would change if the column used DEFAULT ON NULL 'ACTIVE' instead.
Show answer
(a) succeeds, and status is 'ACTIVE' because the column was omitted and the default applies. (b) fails with ORA-01400, because an explicit NULL does not trigger the default and the column is NOT NULL. (c) also fails with ORA-01400, because Oracle treats the empty string as NULL. With DEFAULT ON NULL 'ACTIVE', statements (b) and (c) would both succeed and store 'ACTIVE', because the default replaces an explicit NULL.
Exercise
The table customers already has 5,000 rows, and some have a NULL phone. Write the steps to make phone mandatory with a constraint named customers_phone_nn. What error do you get if you skip the cleanup step?
Show answer
First find and fix the rows, for example UPDATE customers SET phone = 'UNKNOWN' WHERE phone IS NULL;, then run ALTER TABLE customers MODIFY (phone CONSTRAINT customers_phone_nn NOT NULL);. Without the cleanup, Oracle fails with ORA-02296 because null values were found. Choose the placeholder value with care, as discussed in the design guidance.