Skip to content

Oracle Constraints (The Guardrails) βš–οΈΒΆ

Prerequisites: Table Management

Mentor's Note: Without constraints, your database is just a messy notepad. Constraints are the rules that keep your data high-quality. They prevent people from entering negative ages or duplicate IDs. πŸ’‘


🌟 The Scenario: The School Registry 🏫¢

  • Primary Key: Every student must have a unique Roll Number.
  • Not Null: Every student must have a Name.
  • Check: A student's age must be between 5 and 18.
  • Foreign Key: A student can only be assigned to a Class ID that actually exists.

πŸ’» 1. Core SyntaxΒΆ

CREATE TABLE students (
    student_id NUMBER PRIMARY KEY,
    name       VARCHAR2(50) NOT NULL,
    email      VARCHAR2(100) UNIQUE,
    age        NUMBER CHECK (age >= 5),
    city       VARCHAR2(50) DEFAULT 'Surat'
);

πŸ’» 2. Foreign Keys & Referential IntegrityΒΆ

Links two tables together.

ALTER TABLE enrollments 
ADD CONSTRAINT fk_student 
FOREIGN KEY (student_id) REFERENCES students(student_id);

πŸ—οΈ Architect's Note: Performance & Constraints πŸ›‘οΈΒΆ

Constraints aren't just for data quality; they help the Oracle Optimizer. - The Architect's Secret: When Oracle knows a column is NOT NULL, it can skip certain internal checks, making your queries faster. - The Index Trick: Oracle automatically creates an Index for Primary Keys and Unique Keys. - Architect's Tip: Foreign Keys DO NOT get an automatic index. You should almost always create one manually on Foreign Key columns to prevent performance slowdowns during Joins!


πŸ“Š Summary TableΒΆ

Constraint Can be NULL? Unique? Auto-Indexed?
Primary Key ❌ No βœ… Yes βœ… Yes
Unique βœ… Yes βœ… Yes βœ… Yes
Not Null ❌ No -- ❌ No

πŸ“ˆ Learning PathΒΆ