In the world of relational databases, SQL constraints play a crucial role in maintaining data integrity and consistency. These rules enforce specific conditions on the data stored in tables, ensuring that only valid information is entered and maintained.
Constraints are rules applied to columns or tables that limit the type of data that can be stored. They act as a safeguard against incorrect data entry and help maintain the accuracy and reliability of the database.
Ensures that a column cannot have a NULL value.
CREATE TABLE employees (
id INT NOT NULL,
name VARCHAR(50) NOT NULL
);
Guarantees that all values in a column are different.
ALTER TABLE employees
ADD CONSTRAINT unique_email UNIQUE (email);
Uniquely identifies each record in a table.
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100)
);
Establishes a link between data in two tables.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
product_id INT,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
Ensures that all values in a column satisfy a specific condition.
CREATE TABLE employees (
id INT,
age INT CHECK (age >= 18)
);
Specifies a default value for a column when no value is specified.
CREATE TABLE orders (
order_id INT,
order_date DATE DEFAULT CURRENT_DATE
);
SQL provides commands to add, modify, or remove constraints after table creation:
-- Adding a constraint
ALTER TABLE employees
ADD CONSTRAINT check_salary CHECK (salary > 0);
-- Removing a constraint
ALTER TABLE employees
DROP CONSTRAINT check_salary;
SQL constraints are essential tools for maintaining data integrity in relational databases. By implementing appropriate constraints, database designers can ensure that the data remains consistent, accurate, and reliable. As you continue to work with SQL, remember that effective use of constraints is key to building robust and efficient database systems.
For more advanced topics, explore SQL transactions and query optimization techniques to further enhance your database management skills.