MySQL + SQL · Lesson 38

Constraints in MySQL

What are Constraints?

Constraints are rules applied to columns to keep data correct and valid. They are enforced automatically by MySQL.

Main Constraints

ConstraintMeaning
NOT NULLColumn cannot be empty
UNIQUENo duplicate values
PRIMARY KEYUnique + not null
FOREIGN KEYLinks to another table
CHECKValue must satisfy a condition
DEFAULTAuto value if none given

Example

CREATE TABLE students (
  roll_no INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(60) UNIQUE,
  marks INT CHECK (marks BETWEEN 0 AND 100),
  status VARCHAR(10) DEFAULT 'active'
);

Summary

  • Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
  • They keep stored data valid automatically.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp