Constraints enforce rules at the table level to ensure data integrity. Common constraints include:
Ensures a column cannot have NULL values.
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(100) NOT NULL );
Ensures all values in a column are distinct.
CREATE TABLE products ( sku VARCHAR(20) UNIQUE, name VARCHAR(100), price DECIMAL(8,2) );
Uniquely identifies each row and implies NOT NULL and UNIQUE.
CREATE TABLE orders ( order_id INT, customer_id INT, PRIMARY KEY (order_id) );
Enforces referential integrity between two tables.
CREATE TABLE order_items ( item_id INT AUTO_INCREMENT PRIMARY KEY, order_id INT, product_id INT, quantity INT, FOREIGN KEY (order_id) REFERENCES orders(order_id), FOREIGN KEY (product_id) REFERENCES products(sku) );
Specifies a default value for a column when none is provided.
CREATE TABLE posts ( post_id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Ensures values in a column meet a Boolean condition.
CREATE TABLE accounts ( account_id INT AUTO_INCREMENT PRIMARY KEY, balance DECIMAL(10,2), CHECK (balance >= 0) );
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!