Constraints In Sql in SQL
? Constraints in SQL
Constraints are rules applied to columns in a database table to enforce data integrity and validity. They restrict the type of data that can be inserted into a table.
? Common Types of Constraints
| Constraint | Description | Example |
|---|---|---|
| PRIMARY KEY | Uniquely identifies each record in a table. | PRIMARY KEY (id) |
| FOREIGN KEY | Ensures referential integrity between tables. | FOREIGN KEY (dept_id) REFERENCES departments(id) |
| UNIQUE | Ensures all values in a column are unique. | UNIQUE (email) |
| NOT NULL | Ensures a column cannot have NULL values. | name VARCHAR(100) NOT NULL |
| CHECK | Ensures values meet a specific condition. | CHECK (age >= 18) |
| DEFAULT | Sets a default value for a column. | status VARCHAR(10) DEFAULT 'active' |
? How to Add Constraints
During Table Creation
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE, age INT CHECK (age >= 18), dept_id INT, FOREIGN KEY (dept_id) REFERENCES departments(id));On Existing Table
ALTER TABLE employeesADD CONSTRAINT chk_age CHECK (age >= 18);? Why Use Constraints?
Maintain accuracy and reliability of data.
Prevent invalid or inconsistent data entry.
Define relationships between tables.
If you want examples of specific constraints or how to drop constraints, just ask!