Skip to main content

Command Palette

Search for a command to run...

๐Ÿš€ Understanding Constraints in Oracle SQL (PRIMARY KEY, NOT NULL, UNIQUE)

Updated
โ€ข2 min read
๐Ÿš€ Understanding Constraints in Oracle SQL (PRIMARY KEY, NOT NULL, UNIQUE)

As part of my continued learning with Oracle Autonomous Database, I explored constraints in SQL. Constraints are rules applied to table columns to ensure data accuracy and integrity.

๐ŸŽฏ Objective

The goal of this activity was to:

  • Understand different types of constraints

  • Apply constraints while creating tables

  • Ensure data consistency

๐Ÿ’ป Step 1: Creating Table with Constraints

CREATE TABLE students (
  student_id NUMBER PRIMARY KEY,
  name VARCHAR2(50) NOT NULL,
  email VARCHAR2(100) UNIQUE,
  age NUMBER
);

๐Ÿงช Step 2: Inserting Data

INSERT INTO students VALUES (1, 'Ali', 'ali@example.com', 20);
INSERT INTO students VALUES (2, 'Sara', 'sara@example.com', 21);

โŒ Step 3: Testing Constraints

Duplicate PRIMARY KEY

INSERT INTO students VALUES (1, 'Ahmed', 'ahmed@example.com', 22);

This fails because the PRIMARY KEY must be unique.

NULL Value in NOT NULL Column

INSERT INTO students VALUES (3, NULL, 'test@example.com', 23);

This fails because the name column does not allow NULL values.

๐Ÿ“Š Step 4: Viewing Data

SELECT * FROM students;

๐Ÿ’ก What I Learned

  • Role of constraints in database design

  • Enforcing data integrity using PRIMARY KEY, NOT NULL, and UNIQUE

  • Handling invalid data inputs

๐Ÿš€ Conclusion

This activity helped me understand how constraints ensure data accuracy and reliability in Oracle SQL. Constraints are essential for maintaining a clean and consistent database.

3 views