Skip to content

SQL Constraints: The Data Rules βš–οΈΒΆ

Prerequisites: Create Table Basics

Mentor's Note: Constraints are the "Guardrails" of your database. Without them, you could have a student with no name, or a negative salary. Constraints ensure your data stays high-quality and trustworthy. πŸ’‘


🌟 The Scenario: The School Registry 🏫¢

Imagine you are the principal of a school.

  1. NOT NULL: Every student must have a name. πŸ‘€
  2. UNIQUE: No two students can have the same Email ID. πŸ“§
  3. PRIMARY KEY: Every student must have a unique Roll Number to identify them. πŸ†”
  4. CHECK: A student's age must be at least 5 years old. πŸŽ‚
  5. DEFAULT: If no city is provided, assume they are from "Surat". πŸ“

🎨 Visual Logic: The Constraint Guard¢

graph TD
    A[Data Entry πŸ“₯] --> B{Constraints?}
    B -- "Fail ❌" --> C[Reject Action 🚫]
    B -- "Pass βœ…" --> D[Save to Table πŸ—„οΈ]

    subgraph "Rule Set"
    B1[NOT NULL]
    B2[UNIQUE]
    B3[PRIMARY KEY]
    B4[CHECK]
    end

πŸ’» Common Constraints (DDL Syntax)ΒΆ

CREATE TABLE STUDENTS (
    roll_no   NUMBER(5) PRIMARY KEY, -- πŸ†” Unique ID
    name      VARCHAR2(50) NOT NULL, -- πŸ‘€ Mandatory
    email     VARCHAR2(100) UNIQUE,  -- πŸ“§ No Duplicates
    age       NUMBER(3) CHECK (age >= 5), -- πŸŽ‚ Age Rule
    city      VARCHAR2(50) DEFAULT 'Surat' -- πŸ“ Auto-fill
);
CREATE TABLE STUDENTS (
    roll_no   INT PRIMARY KEY AUTO_INCREMENT,
    name      VARCHAR2(50) NOT NULL,
    email     VARCHAR2(100) UNIQUE,
    age       INT CHECK (age >= 5),
    city      VARCHAR2(50) DEFAULT 'Surat'
);

πŸ“– Deep Dive: Primary vs Foreign KeyΒΆ

1. Primary Key (The Anchor βš“)ΒΆ

  • Unique identify for every row.
  • Cannot be NULL.
  • Only one per table.

2. Foreign Key (The Bridge πŸŒ‰)ΒΆ

  • Links one table to another.
  • Points to the Primary Key of another table.
  • Maintains Referential Integrity.
-- πŸŒ‰ Linking Employees to Departments
CREATE TABLE EMPLOYEE (
    emp_id NUMBER PRIMARY KEY,
    dept_id NUMBER REFERENCES DEPARTMENT(dept_id) -- πŸ”— Foreign Key
);

πŸ“Š Comparison TableΒΆ

Constraint Can be NULL? Unique? Limit per Table
PRIMARY KEY ❌ No βœ… Yes Only 1
UNIQUE βœ… Yes βœ… Yes Multiple
NOT NULL ❌ No ❌ No Multiple

πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers often ask: 'Can a UNIQUE constraint have a NULL value?' The answer is YES! In most databases, you can have one (or sometimes multiple) NULL values in a UNIQUE column, because NULL is not equal to NULL."


πŸ“ˆ Learning PathΒΆ


πŸ’‘ Pro Tip: "Bad data is worse than no data. Use constraints early so you don't have to clean up a mess later."