The NOT NULL constraint is used to ensure that a column cannot have a NULL value. This is a basic and important concept in SQL, as it guarantees that the column will always contain data when you insert or update records.
π¨ Pro Tip: NULL represents the absence of data. When you apply the NOT NULL constraint to a column, it ensures that every row in the column contains valid data.
When creating a table, you can specify that a column should not allow NULL values by using the NOT NULL
constraint. Here's how you can do it:
Example: Create a table where the employee_name column must have a value:
CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(100) NOT NULL, department VARCHAR(50) );
In this example, the employee_name
column cannot be left empty when a new record is inserted into the employees
table.
If you try to insert a NULL value into a column that has the NOT NULL
constraint, SQL will throw an error. Here's an example:
Example: Insert a record with missing employee name:
INSERT INTO employees (employee_id, employee_name, department) VALUES (1, NULL, 'HR');
This will cause an error because the employee_name
column has a NOT NULL
constraint, and you are attempting to insert a NULL value.
π οΈ Interactive Task: Try inserting data into the table with both valid and NULL values. What happens when you attempt to insert NULL into the NOT NULL
column?
If you have an existing column and you want to add the NOT NULL
constraint to it, you can use the ALTER TABLE
statement. Here's how:
Example: Alter the employee_name column to be NOT NULL
:
ALTER TABLE employees MODIFY employee_name VARCHAR(100) NOT NULL;
This will enforce that all future records inserted into the table will require a non-NULL value in the employee_name
column.
You can combine the NOT NULL
constraint with other constraints such as PRIMARY KEY
, UNIQUE
, and CHECK
. For example, a column can be both a primary key and NOT NULL:
Example: Creating a table with both NOT NULL
and PRIMARY KEY
constraints:
CREATE TABLE employees ( employee_id INT PRIMARY KEY NOT NULL, employee_name VARCHAR(100) NOT NULL, department VARCHAR(50) );
In this case, both the employee_id
and employee_name
columns are required to contain data, ensuring that the table has valid and non-empty records.
NOT NULL
constraint ensures that your data is always complete and never missing.DEFAULT
constraint alongside NOT NULL
.NOT NULL
constraint because a primary key must contain unique and non-null values.
π― Interactive Task: Try creating a table with a combination of NOT NULL
and other constraints. See how they work together to ensure data integrity.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!