Home >Database >Mysql Tutorial >Detailed explanation of constraints in MySQL
Detailed explanation of constraints in MySQL
In the MySQL database, constraints (constraints) are used to define and limit the value range and data integrity of columns in the table rule. By adding constraints to columns during table creation, you can ensure data correctness and consistency. This article will introduce the commonly used constraint types in MySQL and provide specific code examples.
CREATE TABLE students ( id INT PRIMARY KEY, name VARCHAR(50), age INT );
CREATE TABLE orders ( order_id INT PRIMARY KEY, product_id INT, customer_id INT, FOREIGN KEY (product_id) REFERENCES products(product_id), FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );
CREATE TABLE employees ( employee_id INT PRIMARY KEY, email VARCHAR(50) UNIQUE, department_id INT );
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(50), quantity INT, price DECIMAL(10, 2), CONSTRAINT CHK_quantity CHECK (quantity >= 0), CONSTRAINT CHK_price CHECK (price > 0) );
CREATE TABLE users ( user_id INT PRIMARY KEY, username VARCHAR(50), password VARCHAR(50) DEFAULT '123456', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
The above is an introduction to the commonly used constraint types in MySQL and how to use them. Using constraints ensures data integrity and consistency in your database. By using constraints appropriately, errors and inconsistent data can be reduced, and the efficiency and reliability of the database can be improved. I hope this article can help you understand and use the constraint function of MySQL.
The above is the detailed content of Detailed explanation of constraints in MySQL. For more information, please follow other related articles on the PHP Chinese website!