Databases are required to have accurate and non-duplicate data. Microsoft SQL Server uses constraints for enforcing data rules within a table. This is an all-encompassing tutorial on types of constraints found in SQL Server, along with examples of their application and best practice usage.
Table of Contents
What Are SQL Constraints?
SQL constraints are necessary rules that describe what type of data can be held in a database table. This is achieved through ensuring valid data is inserted into the database by maintaining the integrity of the data. Constraints may apply at either column or table level, meaning it can have some flexibility when rules on data are being applied.
Importance of SQL Constraints
- Data Integrity: Constraints ensure data adheres to defined rules preventing invalid entries.
- Consistency: They ensure uniformity throughout the database, so similar data is treated uniformly.
- Business Logic Enforcement: Constraints directly enforce business rules in the database schema.
- Error Prevention: They reduce the possibility of anomalies and error in the data.
![Become a Database Architect](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20826%20180'%3E%3C/svg%3E)
Types of Constraints in Microsoft SQL Server
NOT NULL Constraint
The NOT NULL constraint is used in ensuring that the column cannot include NULL values so that this column must always hold a value.
CREATE TABLE IntellipaatEmployees (
EmpID INT NOT NULL,
Firstname VARCHAR(50) NOT NULL,
Lastname VARCHAR(50) NOT NULL
);
UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are unique hence not duplicated. Unique constraints are unlike primary keys. With them, only one NULL value is allowed per column.
CREATE TABLE IntellipaatUsers (
UserID INT UNIQUE NOT NULL,
Email VARCHAR(255) UNIQUE NOT NULL
);
PRIMARY KEY Constraint
The PRIMARY KEY uniquely identifies each record in a table. It does both NOT NULL and UNIQUE combinations, meaning it does not accept duplicate or null values.
CREATE TABLE IntellipaatProducts (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100) NOT NULL
);
FOREIGN KEY Constraint
FOREIGN KEY Constraint: The FOREIGN KEY constraint comes into view when two tables are related, based on a reference to some other table’s primary key. This will enforce referential integrity, since any value in the foreign key column must have a corresponding value in the PRIMARY KEY column of the referenced table.
CREATE TABLE IntellipaatOrders (
OrderID INT PRIMARY KEY,
UserID INT,
FOREIGN KEY (UserID) REFERENCES IntellipaatUsers(UserID)
);
CHECK Constraint
A CHECK constraint enables you to create a condition that must be met by values placed in a column. They are very useful in enforcing domain integrity through restricting acceptable values.
CREATE TABLE IntellipaatEmployees (
EmployeeID INT PRIMARY KEY,
Age INT CHECK (Age >= 18)
);
DEFAULT Constraint
The DEFAULT constraint gives a column a default value during an insert operation if no value is specified, ensuring meaningful values even if not explicitly set.
CREATE TABLE IntellipaatSettings (
SettingID INT PRIMARY KEY,
Theme VARCHAR(50) DEFAULT 'Light'
);
How to Create Constraints in SQL Server
Constraints can either be defined upon the creation of a new table or added at a later point using the ALTER TABLE statement.
Creating Constraints During Table Creation
Constraints can be defined in the CREATE TABLE statement itself, as shown in the above example statements.
Adding Constraints After Table Creation
To impose constraints after a table has been created, the user can use an ALTER TABLE statement:
ALTER TABLE IntellipaatEmployees ADD CONSTRAINT chk_Age CHECK (Age >= 18);
Best Practices for Using SQL Constraints
- Use Meaningful Names: Your constraints should have descriptive names so that they become meaningful.
- Apply constraints wisely: Enforce only such constraints as are necessary to maintain data integrity.
- Test Your Constraints: Try a few scenarios to see if your constraints work as planned.
- Document Your Database Schema: Maintain records of all constraints applied to your tables for future reference.
Conclusion
The most important tool used in maintaining data integrity and accuracy within Microsoft SQL Server consists of SQL constraints. Having known about different constraints and how they are properly implemented, you would be able to design proper databases with the correct data management. This is your ultimate guide for SQL constraints which provides all that you would require in order to have rules on your database.
Our SQL Courses Duration and Fees
Cohort starts on 16th Feb 2025
₹15,048
Cohort starts on 23rd Feb 2025
₹15,048