SQL Tutorial
Estimated reading: 4 minutes 33 views

🧷 SQL Constraints and Indexes – NOT NULL, UNIQUE, PRIMARY KEY, INDEX Explained


🧲 Introduction – Why Learn SQL Constraints & Indexes?

When building robust database systems, it’s not enough to just store dataβ€”you must also ensure its accuracy, consistency, and performance. SQL constraints enforce rules on the data, while indexes help accelerate queries.

Learning SQL constraints and indexes helps you:

  • 🚫 Prevent invalid or duplicate entries
  • πŸ”’ Maintain relationships between tables
  • ⚑ Improve query execution times dramatically

🎯 In this guide, you’ll learn how to:

  • Apply constraints like NOT NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, and DEFAULT
  • Use INDEX and AUTO INCREMENT to optimize performance and automate key generation

πŸ“˜ Topics Covered

πŸ”– TopicπŸ“„ Description
🚫 SQL NOT NULLEnsures a column cannot have NULL values
πŸ” SQL UNIQUEEnsures all values in a column are distinct
πŸ”‘ SQL PRIMARY KEYUniquely identifies each row in a table
πŸ”— SQL FOREIGN KEYEstablishes a link between two tables
βœ… SQL CHECKRestricts values in a column using custom logic
🧩 SQL DEFAULTAssigns a default value if no value is provided
πŸ“Œ SQL INDEXImproves performance of SELECT queries
πŸ”’ SQL AUTO INCREMENTAutomatically generates numeric values (e.g., IDs)

🚫 SQL NOT NULL – Enforce Required Fields

CREATE TABLE users (
  id INT,
  name VARCHAR(100) NOT NULL
);

βœ… Ensures that the name column cannot be left empty.
πŸ“Ž Common for essential fields like email, username, or password.


πŸ” SQL UNIQUE – Enforce Distinct Values

CREATE TABLE users (
  email VARCHAR(255) UNIQUE
);

βœ… Prevents duplicate values in a column.
πŸ“Ž Perfect for fields like email or social security numbers.


πŸ”‘ SQL PRIMARY KEY – Identify Rows Uniquely

CREATE TABLE employees (
  emp_id INT PRIMARY KEY,
  name VARCHAR(100)
);

βœ… Uniquely identifies each row and implies NOT NULL + UNIQUE.
πŸ“Ž Only one primary key allowed per table.


πŸ”— SQL FOREIGN KEY – Maintain Relationships

CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES users(id)
);

βœ… Links rows in one table to another, enforcing referential integrity.
πŸ“Ž Prevents insertion of invalid references.


βœ… SQL CHECK – Apply Value Constraints

CREATE TABLE products (
  price DECIMAL(10,2),
  CHECK (price > 0)
);

βœ… Ensures a logical condition is met for values.
πŸ“Ž Use to validate age, price, quantity, etc.


🧩 SQL DEFAULT – Assign Values Automatically

CREATE TABLE tasks (
  status VARCHAR(50) DEFAULT 'pending'
);

βœ… Assigns a default value when no input is provided.
πŸ“Ž Helpful for status, created_at, or boolean flags.


πŸ“Œ SQL INDEX – Boost Query Speed

CREATE INDEX idx_lastname
ON employees (last_name);

βœ… Improves SELECT and JOIN performance.
πŸ“Ž Indexes speed up search but may slow INSERT/UPDATE operations slightly.


πŸ”’ SQL AUTO INCREMENT – Generate Unique IDs

CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100)
);

βœ… Automatically assigns a unique number to new rows.
πŸ“Ž Used for primary key columns like user ID, invoice number, etc.


πŸ“˜ Best Practices for Constraints & Indexes

βœ… Do This❌ Avoid This
Use NOT NULL on required fieldsDon’t allow NULLs unless necessary
Apply UNIQUE to identity columnsAvoid duplicate-sensitive fields without it
Define FOREIGN KEYS for data relationshipsDon’t hard-code foreign relations manually
Use CHECK for business rulesAvoid constraints in app code only
Index frequently queried columnsDon’t over-index β€” it affects write performance
Use AUTO INCREMENT for identityAvoid manual ID generation

πŸ“Œ Summary – Recap & Next Steps

SQL constraints ensure data quality and integrity, while indexes provide the speed needed for large datasets and fast access.

πŸ” Key Takeaways:

  • Constraints (NOT NULL, UNIQUE, CHECK, PRIMARY, FOREIGN) validate data rules
  • Indexes and AUTO INCREMENT optimize performance and automation
  • Proper use of constraints prevents errors and simplifies logic

βš™οΈ Real-World Relevance:
Used in enterprise databases, APIs, CRMs, banking systems, and reporting tools where data correctness and speed are non-negotiable.

➑️ Next Up: Dive into πŸ“Š SQL Indexing Strategies & Query Optimization Techniques.


❓ FAQs – SQL Constraints & Indexes


❓ Can a column be both UNIQUE and NOT NULL?
βœ… Yes! This combination ensures every row has a value, and each value is distinct.


❓ What’s the difference between PRIMARY KEY and UNIQUE?
βœ… PRIMARY KEY implies both NOT NULL and UNIQUE, while UNIQUE allows NULL unless stated otherwise.


❓ How many PRIMARY KEYs can a table have?
βœ… Only one PRIMARY KEY per table, though it can include multiple columns (composite key).


❓ Can I add constraints after table creation?
βœ… Yes, using ALTER TABLE:

ALTER TABLE users ADD CONSTRAINT chk_age CHECK (age >= 18);

❓ Does every column need an index?
βœ… No. Index only those used in frequent queries, JOIN, or WHERE clauses.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧷 SQL Constraints & Indexes

Or Copy Link

CONTENTS
Scroll to Top