Consider this table definition:
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Age INT CHECK (Age >= 18)
);
What happens if you run this insert?
INSERT INTO Employees (ID, Age) VALUES (1, 16);
CHECK constraints prevent invalid data from being inserted.
The CHECK constraint enforces that Age must be 18 or older. Trying to insert 16 violates this rule, so the insert fails.
What is the main purpose of a CHECK constraint in a database table?
Think about data validation rules inside a table.
CHECK constraints ensure that only values meeting a condition can be stored in a column, helping keep data valid.
Which of the following SQL statements correctly adds a CHECK constraint to ensure salary is positive?
CHECK conditions must be enclosed in parentheses.
The correct syntax requires the CHECK condition inside parentheses and the CONSTRAINT keyword before the name.
Given this table creation:
CREATE TABLE Products (
ID INT PRIMARY KEY,
Price DECIMAL(10,2),
CHECK Price > 0
);
Why does the database allow inserting a product with Price = -5?
Look carefully at the CHECK syntax.
CHECK constraints require the condition to be enclosed in parentheses. Without them, the constraint is ignored or misinterpreted.
You have a large table with a CHECK constraint on a complex expression involving multiple columns. What is the best way to optimize performance when inserting many rows?
Think about how constraints affect bulk operations.
Disabling the CHECK constraint during bulk inserts avoids repeated checks, improving speed. Re-enabling afterward ensures data integrity.