MySQL + SQL · Lesson 16

Keys and Constraints in DBMS

What are Keys?

Keys are one or more columns in a table that are used to uniquely identify each row, establish relationships between tables, and ensure data integrity. Keys are the backbone of a relational database design.

Without keys, a database cannot:

  • Distinguish between two students named "Aarav Sharma".
  • Link fee records to the correct student.
  • Prevent duplicate or incorrect data entry.

Types of Keys in DBMS

Key TypeDefinitionSchool Example
Primary KeyUniquely identifies each row. Cannot be NULL or duplicate.roll_no in students table — each student has unique roll number
Foreign KeyA column that refers to the PRIMARY KEY of another table. Maintains referential integrity.roll_no in fee_records refers to roll_no in students table
Candidate KeyAny column that can become a primary key — unique and not null.roll_no, aadhar_no, email — all can uniquely identify a student
Super KeyAny combination of columns that uniquely identifies a row (includes candidate keys + extra columns).{roll_no}, {roll_no, name}, {aadhar_no, city} — all are super keys
Alternate KeyCandidate keys not chosen as primary key.If roll_no is primary key, then aadhar_no and email are alternate keys
Composite KeyPrimary key made of TWO or more columns together.In exam_results: {roll_no + subject} together identify one unique mark entry
Unique KeyEnsures uniqueness like primary key but allows ONE NULL value.email in students — unique but student may not have email yet

What are Constraints?

Constraints are rules applied to columns that automatically prevent invalid, incorrect or inconsistent data from entering the database. They enforce data integrity without any extra programming.

Constraints are defined while creating a table using CREATE TABLE or added later using ALTER TABLE.

Types of Constraints in MySQL

ConstraintMeaningExample
NOT NULLColumn cannot be left empty — value is mandatoryStudent name must always be entered
UNIQUEAll values in column must be different — duplicates not allowedEmail ID must be different for every student
PRIMARY KEYUnique + NOT NULL — main identifier of each rowroll_no: no two students can have same roll, and it must exist
FOREIGN KEYLinks to PRIMARY KEY of another table — prevents orphan recordsfee_records.roll_no must exist in students.roll_no
CHECKValidates data against a condition — rejects invalid valuesmarks must be between 0 and 100; age must be > 5
DEFAULTSets automatic value if no value is provided during INSERTattendance defaults to 'P' (present) if not specified
AUTO_INCREMENTAutomatically generates next number — no manual entry neededfee_id: 1, 2, 3... automatically assigned

SQL Examples with Output

Complete School Database with Keys and Constraints

CREATE DATABASE school_db;
USE school_db;

-- PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT
CREATE TABLE students (
  roll_no INT PRIMARY KEY,                          -- PRIMARY KEY: unique + not null
  name VARCHAR(80) NOT NULL,                        -- NOT NULL: name required
  email VARCHAR(100) UNIQUE,                        -- UNIQUE: no duplicate emails
  gender CHAR(1) DEFAULT 'M',                       -- DEFAULT: M if not specified
  city VARCHAR(50) NOT NULL
);

-- FOREIGN KEY, CHECK, AUTO_INCREMENT
CREATE TABLE marks (
  mark_id INT AUTO_INCREMENT PRIMARY KEY,           -- AUTO_INCREMENT: auto ID
  roll_no INT NOT NULL,
  subject VARCHAR(40) NOT NULL,
  marks INT CHECK (marks BETWEEN 0 AND 100),        -- CHECK: marks must be 0-100
  FOREIGN KEY (roll_no) REFERENCES students(roll_no) -- FOREIGN KEY: must exist in students
    ON DELETE CASCADE                               -- if student deleted, marks deleted too
);

-- COMPOSITE KEY example
CREATE TABLE exam_schedule (
  roll_no INT,
  subject VARCHAR(40),
  exam_date DATE,
  room_no INT,
  PRIMARY KEY (roll_no, subject),                   -- COMPOSITE KEY: both together = unique
  FOREIGN KEY (roll_no) REFERENCES students(roll_no)
);

Insert Data – Constraint Validation in Action

-- Correct insert
INSERT INTO students VALUES (1, 'Aarav Sharma', 'aarav@email.com', 'M', 'Khurja');
INSERT INTO students VALUES (2, 'Priya Verma', 'priya@email.com', 'F', 'Aligarh');

-- This will FAIL — duplicate roll_no (PRIMARY KEY violation)
INSERT INTO students VALUES (1, 'Ravi Singh', 'ravi@email.com', 'M', 'Meerut');
-- ERROR 1062: Duplicate entry '1' for key 'PRIMARY'

-- This will FAIL — marks out of range (CHECK violation)
INSERT INTO marks (roll_no, subject, marks) VALUES (1, 'Math', 110);
-- ERROR 3819: Check constraint violated

-- This will FAIL — roll_no 99 doesn't exist in students (FOREIGN KEY violation)
INSERT INTO marks (roll_no, subject, marks) VALUES (99, 'Math', 85);
-- ERROR 1452: Cannot add or update a child row: foreign key constraint fails

-- DEFAULT test — gender not provided, will be 'M' automatically
INSERT INTO students (roll_no, name, email, city) VALUES (3, 'Neha Gupta', 'neha@email.com', 'Agra');
SELECT * FROM students WHERE roll_no = 3;
Output for DEFAULT test:
+---------+------------+------------------+--------+------+
| roll_no | name | email | gender | city |
+---------+------------+------------------+--------+------+
| 3 | Neha Gupta | neha@email.com | M | Agra |
+---------+------------+------------------+--------+------+
Gender defaulted to 'M' automatically — no error.

Adding Constraints Later with ALTER TABLE

-- Add NOT NULL constraint to existing column
ALTER TABLE students MODIFY city VARCHAR(50) NOT NULL;

-- Add UNIQUE constraint to existing column
ALTER TABLE students ADD CONSTRAINT uq_email UNIQUE (email);

-- Add CHECK constraint
ALTER TABLE marks ADD CONSTRAINT chk_marks CHECK (marks >= 0 AND marks <= 100);

-- Add FOREIGN KEY to existing table
ALTER TABLE marks ADD CONSTRAINT fk_roll
  FOREIGN KEY (roll_no) REFERENCES students(roll_no);

-- Remove a constraint
ALTER TABLE marks DROP CONSTRAINT chk_marks;

Common Mistakes

  • Forgetting PRIMARY KEY: Table without primary key allows duplicate rows — data becomes unreliable.
  • Confusing UNIQUE with PRIMARY KEY: UNIQUE allows one NULL; PRIMARY KEY never allows NULL. A table can have many UNIQUE columns but only one PRIMARY KEY.
  • FOREIGN KEY mismatch: Data types of foreign key and referenced primary key must match exactly (both INT, or both VARCHAR with same length).
  • CHECK constraint in old MySQL: MySQL 5.7 and earlier accepted CHECK syntax but did NOT enforce it. CHECK is enforced only from MySQL 8.0+.
  • Deleting parent record with child data: Deleting a student who has fee records → FOREIGN KEY error unless ON DELETE CASCADE is set.
  • Not naming constraints: Always name important constraints (CONSTRAINT fk_roll FOREIGN KEY...) so they can be dropped later easily.

Practice Tasks

  1. Create a library_db with books table (book_id PRIMARY KEY, title NOT NULL, isbn UNIQUE, available_copies CHECK >= 0) and issued_books table with FOREIGN KEY to both books and students.
  2. Try inserting a row that violates each constraint (NOT NULL, UNIQUE, CHECK, FOREIGN KEY) and write the exact error message you get.
  3. Write a table showing all 7 types of keys with 1 example each from a hospital database (patients, doctors, appointments).
  4. Viva Q: "What is the difference between PRIMARY KEY and UNIQUE KEY?" — Answer in 4 points.

Summary

  • Keys identify rows and link tables — Primary, Foreign, Candidate, Super, Alternate, Composite, Unique.
  • Constraints enforce data rules automatically — NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
  • PRIMARY KEY = Unique + NOT NULL. UNIQUE = Unique + allows one NULL.
  • FOREIGN KEY ensures referential integrity — child record must have matching parent.
  • CHECK is enforced from MySQL 8.0+. AUTO_INCREMENT generates automatic sequential IDs.
  • Always design keys and constraints at table creation time — they save enormous debugging time later.