smartyfy.mrindigi.com

Databases & SQL Master Course — 061. NOT NULL and Required Values

Lesson 061 NOT NULL and Required Values

Prerequisites and objectives

You can rehearse writes and inspect constraint errors. This lesson separates a missing value from an empty or unsuitable value. You will enforce required columns with NOT NULL, explain how omission interacts with defaults, and add a narrowly defined blank-label rule without claiming that it validates every possible name.

Create the practice fixture

Use a fresh disposable SQLite database. The first table requires a label but imposes no nonblank rule. The second table also rejects labels that become empty after trimming ordinary spaces. Every write example is rolled back. Expected errors are part of the test; if your editor stops, run the remaining inspection and rollback statements separately.

CREATE TABLE basic_labels (
 label_id INTEGER PRIMARY KEY,
 label TEXT NOT NULL,
 status TEXT NOT NULL DEFAULT 'Draft'
);
CREATE TABLE checked_labels (
 label_id INTEGER PRIMARY KEY,
 label TEXT NOT NULL CHECK(length(trim(label))>0)
);
INSERT INTO basic_labels(label_id,label) VALUES (1,'Shelf A');

Separate missing from present but empty

NULL means that a value is absent or unknown according to the column’s documented meaning. An empty text value is still a value. A string containing three spaces is also present. NOT NULL draws only the missing-versus-present boundary. It cannot establish that a label is meaningful to a person.

Our basic table accepts an empty label. That is not an engine failure: the schema never prohibited it. This distinction matters when a form sends empty text for an unanswered field. An application and database can disagree about what required means unless the rule is written precisely.

BEGIN;
INSERT INTO basic_labels(label_id,label) VALUES (2,'');
SELECT label_id,length(label),status FROM basic_labels ORDER BY label_id;
INSERT INTO basic_labels(label_id,label) VALUES (3,NULL);
ROLLBACK;

The empty label has length zero and receives the default Draft status. The explicit NULL label is rejected. Observe both results rather than interpreting a successful insert as proof that all business validation happened. Constraint tests should include accepted edge cases as well as rejected examples.

A table tests NULL, empty text, three ordinary spaces and padded Shelf C. NOT NULL rejects only NULL. Combining NOT NULL with positive trimmed length also rejects empty and space-only values, while the padded label passes without modifying its stored padding. Omitting status supplies Draft; explicitly setting status NULL is rejected.
A required field can still contain empty text. Specify presence, nonblank content, normalization and defaults as distinct rules. Open full-size diagram

Combine independent rules

The checked table combines two requirements: a label must exist, and its trimmed length must be positive. NOT NULL handles absence; CHECK handles the present string. Keeping these responsibilities distinct makes an error easier to explain and a future policy change easier to review.

SQLite trim without a second argument removes ordinary space characters at the ends. It is not a universal whitespace or Unicode normalization policy. Tabs, nonbreaking spaces, mixed scripts, and invisible characters require a deliberately specified validation approach. Do not promise that this short expression proves every accepted label is readable or safe for every output context.

Understand omission and defaults

When an INSERT omits status, the declared default supplies Draft. When it explicitly supplies NULL under ordinary INSERT behavior, NOT NULL rejects that NULL; the default is not a universal replacement for every missing-looking input. A required column without a default cannot be omitted successfully because the resulting absent value violates the requirement.

Defaults express a legitimate initial state, not a way to hide unknown facts. If the creator’s department is genuinely unknown, automatically labeling it Sales could make the dataset confidently wrong. Choose a documented optional value or require the real answer before insertion, depending on the workflow.

Review a required-field contract

For each field, ask four questions: may it be absent, may it be empty, may it contain surrounding spaces, and is there a truthful default? These questions can have different answers. A middle-name field may be optional, while a stock code may require exact nonblank text. Avoid applying one global cleanup rule to every column simply because it is convenient.

Remember that an outer join can produce a NULL in a query result even when the stored source column is NOT NULL. That NULL represents a missing joined row rather than an accepted NULL stored in the constrained table. Schema guarantees describe stored rows; query construction still affects output meaning.

Four worked exercises

Exercise 1

Insert a basic label while omitting status, then inspect the default.

Worked solution
BEGIN;
INSERT INTO basic_labels(label_id,label) VALUES (2,'Shelf B');
SELECT status FROM basic_labels WHERE label_id=2;
ROLLBACK;

The omitted column receives Draft. The label itself was explicitly provided, so both required columns have values. This result does not imply that every omitted required column can be filled automatically.

Exercise 2

Try explicitly setting the required status to NULL.

Worked solution
BEGIN;
INSERT INTO basic_labels VALUES (2,'Shelf B',NULL);
SELECT COUNT(*) FROM basic_labels;
ROLLBACK;

The insert fails and the table retains its original row. Under the ordinary conflict behavior used here, the explicit NULL does not invoke the default. Applications should distinguish omitted fields from explicitly supplied values.

Exercise 3

Test a space-only label against the stronger rule, then insert a padded valid label.

Worked solution
BEGIN;
INSERT INTO checked_labels VALUES (1,'   ');
INSERT INTO checked_labels VALUES (2,' Shelf C ');
SELECT label,length(label) FROM checked_labels;
ROLLBACK;

The space-only value fails, while the padded label passes. The constraint tests a trimmed expression but does not rewrite the stored text. If canonical trimming is required, normalization needs its own documented step.

Exercise 4

Omit the required label from a basic insert and explain the failure.

Worked solution
BEGIN;
INSERT INTO basic_labels(label_id) VALUES (2);
SELECT COUNT(*) FROM basic_labels;
ROLLBACK;

The label column has no default, so omission leaves it without a permitted value. The status default cannot supply another column’s value. A useful error message should ask for the missing label rather than silently invent one.

Knowledge check

Question 1

Which value does NOT NULL alone reject?

  1. An empty string
  2. NULL
  3. Three ordinary spaces
  4. A short but valid label
Answer and explanation

B. NOT NULL enforces presence, while blank and content rules need separate requirements.

Question 2

Why does a padded label remain padded?

  1. trim is applied only when values are selected
  2. NOT NULL normalizes text before storing it
  3. CHECK expressions rewrite values only on UPDATE
  4. CHECK validates an expression without normalizing storage
Answer and explanation

D. The rule can inspect a transformed value without assigning that transformation back.

Question 3

What happens when status is omitted here?

  1. NULL is stored despite NOT NULL
  2. Draft is supplied by its default
  3. The whole row is always rejected
  4. The previous row’s status is copied
Answer and explanation

B. The column has a declared default that satisfies its required-value constraint.

Question 4

Why avoid a fictional default department?

  1. It can turn unknown information into false information
  2. Required columns cannot legitimately have any default
  3. Defaults replace even explicitly supplied non-NULL values
  4. An existing default prevents future corrections
Answer and explanation

A. A default should represent a truthful initial state, not conceal missing facts.

Question 5

Can a LEFT JOIN display NULL for a source NOT NULL column?

  1. No, because all result columns inherit stored constraints
  2. Only after disabling foreign keys
  3. Yes, when there is no matching source row
  4. Only if the source table is empty
Answer and explanation

C. Outer-join extension can introduce missing result values without violating the source table.

Pitfalls and summary

Do not use required as an undefined synonym for valid. Distinguish absence, emptiness, whitespace, and normalization. Test omitted and explicit NULL inputs separately, and avoid defaults that invent facts. Combining small, clearly named responsibilities produces a schema whose guarantees are easier to explain and whose limits are easier to recognize.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references