bhylu.com

Advertisements

SQL Not Null

NOT NULL requires a value to be present. Use it when a record without that value would be incomplete, such as an order that has no status. Missing data and invalid-looking text are different checks.

Understand the idea

Our contact table requires a display name. Supplying a name satisfies NOT NULL, but an empty string would also satisfy it because an empty string is still a value in SQLite. If blank names are invalid, add a suitable CHECK and application validation. Define missingness rules deliberately instead of filling every unknown field with placeholder text.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

CREATE TABLE contacts (
  contact_id INTEGER PRIMARY KEY,
  display_name TEXT NOT NULL
);
INSERT INTO contacts VALUES (1, 'Workshop desk');
SELECT * FROM contacts;

Read the result

The row is accepted because display_name has a value. Replacing that value with NULL causes a constraint error. The identifier remains a separate rule.

Try one change

Add CHECK (length(trim(display_name)) > 0), then compare a real name with a string containing only spaces.