Constraints are rules that govern the data stored in a table. They protect data accuracy, prevent duplicates, and keep relationships intact.
• NOT NULL — a value can't be left empty
• UNIQUE — the value can't be duplicated
• PRIMARY KEY — uniquely identifies a row
• FOREIGN KEY — links two tables together in a relationship
• DEFAULT — sets a default value when none is provided
sql
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL UNIQUE,
CustomerID int,
OrderStatus varchar(50) DEFAULT 'pending',
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);You should see
What this code does: It builds the Orders table with constraints in place. OrderID is the primary key, OrderNumber is unique, and CustomerID is a foreign key linking to the Customers table. Why it matters: This helps stop orders from being added for customers that don't exist, keeps order numbers from duplicating, and defaults the status to pending when none is given.