How to use check constraint for gender in mysql?

In MySQL, you can use the ENUM data type to define a gender field and restrict the range of values using a CHECK constraint, thus enforcing gender constraints. Here is an example:

CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    gender ENUM('Male', 'Female') NOT NULL
);

ALTER TABLE users
ADD CONSTRAINT check_gender CHECK (gender IN ('Male', 'Female'));

In the example above, a table named ‘users’ was created with fields for id, name, and gender. The gender field is defined using ENUM(‘Male’, ‘Female’) to specify two possible values, male and female. A CHECK constraint named ‘check_gender’ was then added to the table using the ALTER TABLE statement to restrict the gender field to only accept ‘Male’ or ‘Female’ as values.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds