Concept Flow - NOT NULL constraint
Define Table with NOT NULL
Insert Row
Check Column Value
Error: Reject
When inserting data, the database checks if columns with NOT NULL have values. If a NULL is found, insertion is rejected.
Jump into concepts and practice - no test required
CREATE TABLE users ( id INT NOT NULL, name VARCHAR(50) NOT NULL ); INSERT INTO users (id, name) VALUES (1, 'Alice'); INSERT INTO users (id, name) VALUES (2, NULL);
| Step | Action | Column Checked | Value | Result | Notes |
|---|---|---|---|---|---|
| 1 | Create table | id, name | N/A | Success | Table created with NOT NULL constraints |
| 2 | Insert row | id | 1 | Valid | Value is NOT NULL |
| 2 | Insert row | name | 'Alice' | Valid | Value is NOT NULL |
| 2 | Insert row | All columns | Valid | Row inserted | Row with id=1 and name='Alice' added |
| 3 | Insert row | id | 2 | Valid | Value is NOT NULL |
| 3 | Insert row | name | NULL | Invalid | NOT NULL constraint violated |
| 3 | Insert row | All columns | Invalid | Error | Insertion rejected due to NULL in NOT NULL column |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| users table rows | empty | [{id:1, name:'Alice'}] | [{id:1, name:'Alice'}] | [{id:1, name:'Alice'}] |
NOT NULL constraint ensures a column cannot have NULL values. When inserting or updating, NULL in NOT NULL columns causes error. Valid values include empty strings or zero, but not NULL. Use NOT NULL to enforce required data in columns.
What does the NOT NULL constraint do in a database table?
Which of the following is the correct syntax to add a NOT NULL constraint to a column named email when creating a table?
CREATE TABLE users (
id INT PRIMARY KEY,
email ???
);
Given the table employees with columns id INT PRIMARY KEY and name VARCHAR(100) NOT NULL, what happens when you run this query?
INSERT INTO employees (id, name) VALUES (1, NULL);
Consider this table creation statement:
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
price DECIMAL(5,2)
);
Which of the following statements will cause an error?
You have a table orders with columns order_id INT PRIMARY KEY, customer_id INT NOT NULL, and order_date DATE NOT NULL. You want to add a new column status that must always have a value and defaults to 'pending'. Which is the correct way to add this column?