SQL constraint is a rule applied to the 'column(s)', that restricts the values that can be entered into that column(s).
Constraints can be defined during the table creation by using "CREATE TABLE statement" or added to an existing table using "ALTER TABLE statement". They remain in place until explicitly removed or modified.
CREATE TABLE Employee ( [Id] INT PRIMARY KEY, [First_Name] VARCHAR(50) NOT NULL, [Last_Name] VARCHAR(50) NOT NULL, [Email] VARCHAR(255) UNIQUE, [Age] INT CHECK (age >= 18), [Salary] DECIMAL(10,2) DEFAULT 0, [Department_Id] INT REFERENCES Department(id) ON DELETE CASCADE );
PRIMARY KEY constraint on [Id] column to ensure that each employee has a unique ID.
NOT NULL constraints on the [FirstName] and [LastName] columns to ensure that these fields cannot be left empty.
UNIQUE constraint on the [Email] column to ensure that each email address is unique.
CHECK constraint on the [Age] column to ensure that employee are at least 18 years old.
DEFAULT constraint on the [Salary] column to set the default value to the [Salary] if no value is specified during an insert operation.
FOREIGN KEY constraint is used to establish a relationship between two tables. The FOREIGN KEY constraint is added to a column in one table that references the PRIMARY KEY column of another table. This constraint ensures that the values in the referencing column must match the values in the referenced column or be null. It can also enable the use of cascading updates and deletes, which can automatically update or delete related records in the referenced table when a record in the referencing table is modified or deleted.
Five constraints in SQL include: Primary Key, Foreign Key, Unique, Not Null, and Check constraints.
Constraints in RDBMS enforce rules or conditions on data stored in tables to maintain data integrity.
SQL supports multiple constraints, including the ones mentioned earlier, but the exact number varies based on the database system.
To query constraints in SQL Server, you can use system tables like sys.check_constraints and sys.foreign_keys to retrieve information about existing constraints in a database.