CHECK & DEFAULT Constraints βοΈΒΆ
Prerequisites: CREATE TABLE
Mentor's Note: Constraints aren't just for uniqueness. They can also act as "Smart Assistants."
DEFAULTsaves you time by auto-filling data, andCHECKensures your data makes logical sense (like no negative salaries!). π‘
π The Scenario: The Online Store πΒΆ
Imagine you are managing an inventory system.
- DEFAULT: If you don't specify a shipping city, the computer assumes it's "Surat". π
- CHECK: The system refuses to save a product if the Stock Count is less than zero. (You can't have negative boxes!). π«
π» 1. The DEFAULT ConstraintΒΆ
Automatically fills a column with a value if the INSERT statement leaves it blank.
SyntaxΒΆ
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE DEFAULT SYSDATE, -- π
Auto-fill today's date
city VARCHAR(50) DEFAULT 'Surat' -- π Default local city
);
How it worksΒΆ
-- Inserting only the ID
INSERT INTO orders (order_id) VALUES (501);
-- Result: [501, 2026-02-15, 'Surat']
π» 2. The CHECK ConstraintΒΆ
Forces a logical rule on the data. If the rule is violated, the row is rejected.
SyntaxΒΆ
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
salary DECIMAL(10, 2) CHECK (salary >= 15000), -- π° Min wage rule
age INT CHECK (age BETWEEN 18 AND 65) -- π Working age rule
);
Adding to an Existing TableΒΆ
π¨ Visual Logic: The Quality FilterΒΆ
graph LR
A[Value: -10] --> B{CHECK stock >= 0}
B -- "False" --> C[Reject Entry β]
D[No City Provided] --> E{Has DEFAULT?}
E -- "Yes" --> F[Insert 'Surat' β
]
π‘ Interview Tip πΒΆ
"Can a
CHECKconstraint reference columns in other tables? No.CHECKcan only validate data within its own row. If you need to check data in other tables, you must use a Trigger."