How can constraints be added to fields in MySQL?
MySQL allows you to add constraints to fields by using the `CONSTRAINT` keyword when creating a table. One common type of constraint is `NOT NULL`, which ensures that the value in the field is not empty.
CREATE TABLE table_name (column_name data_type NOT NULL
);
Unique constraint: ensures that the value in the field is unique within the table.
CREATE TABLE table_name (column_name data_type UNIQUE
);
3. A `PRIMARY KEY` constraint ensures that the values in a field are unique within a table and are used as the primary key for the table.
CREATE TABLE table_name (column_name data_type PRIMARY KEY
);
4. `FOREIGN KEY` constraint: ensures that the values of a field match the primary key or unique key of another table.
CREATE TABLE table_name1 (column_name1 data_type,
column_name2 data_type,
FOREIGN KEY (column_name1) REFERENCES table_name2(column_name2)
);
CHECK constraint: ensures that values in a field meet specified conditions.
CREATE TABLE table_name (column_name data_type,
CHECK (condition)
);
6. `DEFAULT` constraint: Setting a default value for a field.
CREATE TABLE table_name (column_name data_type DEFAULT default_value
);
These constraints can also be added after table creation using the `ALTER TABLE` statement.
ALTER TABLE table_nameADD CONSTRAINT constraint_name constraint_type (column_name);