In MySQL, Constraints are rules that are applied to the columns of a table to ensure the integrity and consistency of the data stored in the database.
Constraints define certain conditions that must be satisfied for data manipulation operations (such as INSERT, UPDATE, or DELETE) to be allowed.
Ensures that each row in a table can be uniquely identified by a specific column or combination of columns.
CREATE TABLE products ( product_code INT PRIMARY KEY, product_name VARCHAR(50) );
Ensures that the values in a column (or a set of columns) are unique across all rows in the table.
CREATE TABLE products ( product_code INT, product_id VARCHAR(50) UNIQUE, ... );
Establishes a link between two tables by enforcing referential integrity.
CREATE TABLE orders ( order_id INT PRIMARY KEY, product_id INT, FOREIGN KEY (product_id) REFERENCES products(product_id) );
Ensures that a column cannot have a NULL value.
CREATE TABLE customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(50) NOT NULL );
Specifies a condition that must be true for each row in a table.
CREATE TABLE products ( product_id INT PRIMARY KEY, price DECIMAL(10, 2) CHECK (price >= 0) );