Junior — Middle
How can a restriction be imposed on the value of a field in an SQL database table?
sobes.tech AI
Answer from AI
In SQL, constraints are used to impose restrictions on the values of a field in a table. The main types of constraints that can be applied to a field:
- CHECK — sets a condition that the field's values must satisfy.
- NOT NULL — prohibits storing NULL in the field.
- UNIQUE — guarantees the uniqueness of the value.
- PRIMARY KEY — a unique identifier for a record.
For example, to restrict the age field to values from 18 to 65, you can use a CHECK constraint:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT CHECK (age >= 18 AND age <= 65)
);
If the table is already created, you can add a constraint using ALTER TABLE:
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age >= 18 AND age <= 65);