In this lecture, we cover SQL Constraints — the rules applied to table columns to ensure data validity, integrity, and consistency. We will explore different types of constraints, their syntax, and practical MySQL examples.
Topics Covered:
NOT NULL: Ensure a column cannot have NULL values
CREATE TABLE students (
id INT NOT NULL,
name VARCHAR(50) NOT NULL
);
UNIQUE: Ensure all values in a column are distinct
CREATE TABLE users (
email VARCHAR(100) UNIQUE
);
PRIMARY KEY: Uniquely identify each row (implies NOT NULL + UNIQUE)
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50)
);
CHECK: Limit values in a column based on a condition
CREATE TABLE products (
price DECIMAL(10,2) CHECK (price operator 0)
);
DEFAULT: Provide a default value if none is supplied
CREATE TABLE accounts (
status VARCHAR(20) DEFAULT 'active'
);
Extra: We’ll also see how to add, drop, and modify constraints using ALTER TABLE.
By the end of this lecture, you’ll know how to design robust tables with constraints to protect your database from invalid data.