Popular

IT Profile

Database basic - part 4: Constraints

Hello everyone, this is the next article in the Database basic tutorial. In this, we will learn about constraints in mysql.

In MySQL, a constraint is a rule applied to columns in a table to enforce data integrity and consistency. Constraints ensure that the data stored in the database follow to certain rules. Constraints are used to prevent invalid data entry and to maintain the accuracy and reliability of the data within the database.


Before we go into the details of each type of constraint, let's review the syntax of the table creation statement that uses constraints. As you see, we have new parts, those are the constraints

CREATE TABLE table_name (

name_column_1 data_type constraints,

name_column_2 data_type constraints,

);



1. Primary key: A primary key constraint is a rule applied to a column or a set of columns in a database table to ensure that the values in these columns are unique and not null. The primary key uniquely identifies each record in the table.

2. Foreign key: A foreign key constraint is a rule applied to a column or set of columns in a database table to ensure that the values in these columns match values in the primary key or unique key of another table. This constraint enforces referential integrity between the two tables, ensuring that relationships between tables are maintained correctly.

3. Unique key: A unique key is a constraint applied to a column or a set of columns in a database table to ensure that all values in the specified column(s) are unique across the entire table. Unlike the primary key, a table can have multiple unique keys, and unique key columns can accept NULL values (but only one NULL value per unique column)

4. Default: A default constraint in MySQL is a rule that assigns a default value to a column when no specific value is provided during an insert operation. This constraint ensures that a column always has a valid value, even if no value is explicitly specified

5. NOT NULL: The NOT NULL constraint in MySQL is used to ensure that a column cannot have a NULL value

6. Check: The CHECK constraint in MySQL is used to enforce a condition that must be met by the values in a column


Comments