Data constraints (NOT NULL, UNIQUE, CHECK) in MYSQL
In MySQL, you can enforce data constraints like NOT NULL, UNIQUE, and CHECK using various methods:
NOT NULL Constraint:
The NOT NULL constraint ensures that a column cannot contain NULL values, meaning every row in that column must have a value.
You can specify this constraint when creating a table or altering an existing table.
Example:
sql code
CREATE TABLE employees (
employee_id INT NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
hire_date DATE NOT NULL
);
UNIQUE Constraint:
The UNIQUE constraint ensures that all values in a column (or combination of columns) are unique across all rows in the table.
You can specify this constraint when creating a table or altering an existing table.
Example:
sql code
CREATE TABLE students (
student_id INT PRIMARY KEY,
student_email VARCHAR(100) UNIQUE
);
CHECK Constraint:
The CHECK constraint allows you to define custom conditions that data in a column must meet.
It's used to ensure that data entered into a column satisfies a specific condition.
The condition can be any valid SQL expression.
Example:
sql code
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
total_amount DECIMAL(10, 2) CHECK (total_amount >= 0)
);
In this example, the CHECK constraint ensures that the total_amount is always greater than or equal to zero.
Remember that the CHECK constraint is available in MySQL starting from version 8.0.23. Prior to that, you might need to use triggers or application-level validation to achieve similar functionality.
Additionally, you can also enforce these constraints at the application level if necessary, but using database constraints is generally a good practice to ensure data integrity.
Comments
Post a Comment