Constraints in SQL
Constraints in SQL are rules applied to table columns to enforce data integrity and consistency. They help ensure that the data entered into a table follows specific rules, such as uniqueness, non-nullability, valid relationships, and more. Common constraints include NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. Constraints can be defined at the time of table creation or added later using the ALTER TABLE command.
NOT NULL Constraint
The NOT NULL constraint in SQL ensures that a column cannot have a NULL value.
It is used when you want to enforce that certain fields must always have a value when inserting or updating a record.
Syntax
CREATE TABLE table_name (
column_name datatype NOT NULL
);
Or when altering an existing table:
ALTER TABLE table_name
MODIFY column_name datatype NOT NULL;
Example
Let’s create a students table where the name column must not be null:
CREATE TABLE students (
student_id INT,
name VARCHAR(50) NOT NULL,
age INT
);
Now if someone tries to insert a student without a name:
INSERT INTO students (student_id, age)
VALUES (1, 20);
❌ This will result in an error because name is required.
When to Use NOT NULL?
-
When a column must always contain a value
-
For important fields like:
- Usernames
- Email addresses
- Primary identifiers
Next, we’ll explore the UNIQUE constraint, which ensures no duplicate values in a column.