Integrity constraints: Primary and Foreign keys
Integrity Constraints: Primary and Foreign Keys Primary Keys A primary key is a unique identifier used to uniquely identify each record in a table. It i...
Integrity Constraints: Primary and Foreign Keys Primary Keys A primary key is a unique identifier used to uniquely identify each record in a table. It i...
Integrity Constraints: Primary and Foreign Keys
Primary Keys
A primary key is a unique identifier used to uniquely identify each record in a table. It is a mandatory column that must contain a valid value for each record. Primary keys can be either integer or string data types.
Example:
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
Foreign Keys
A foreign key is a constraint that enforces a relationship between two tables. This means that the records in the two tables must have the same values in corresponding columns. Foreign keys can be either integer or string data types.
Example:
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT FOREIGN KEY REFERENCES customers(id)
);
Benefits of Integrity Constraints
Data integrity: Integrity constraints help maintain the integrity of the database by preventing invalid or duplicate data entries.
Data consistency: Foreign keys enforce consistency between tables, ensuring that the values in related columns match.
Data security: Primary keys and foreign keys can help prevent unauthorized access to sensitive data.
Summary
Integrity constraints are essential for maintaining data integrity and consistency in a database. Primary keys are used to uniquely identify records, while foreign keys enforce relationships between tables. By using integrity constraints, we can ensure that the data in our database is accurate, consistent, and secure