π§· 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
, andDEFAULT
- Use
INDEX
andAUTO INCREMENT
to optimize performance and automate key generation
π Topics Covered
π Topic | π Description |
---|---|
π« SQL NOT NULL | Ensures a column cannot have NULL values |
π SQL UNIQUE | Ensures all values in a column are distinct |
π SQL PRIMARY KEY | Uniquely identifies each row in a table |
π SQL FOREIGN KEY | Establishes a link between two tables |
β SQL CHECK | Restricts values in a column using custom logic |
π§© SQL DEFAULT | Assigns a default value if no value is provided |
π SQL INDEX | Improves performance of SELECT queries |
π’ SQL AUTO INCREMENT | Automatically 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 fields | Donβt allow NULLs unless necessary |
Apply UNIQUE to identity columns | Avoid duplicate-sensitive fields without it |
Define FOREIGN KEYS for data relationships | Donβt hard-code foreign relations manually |
Use CHECK for business rules | Avoid constraints in app code only |
Index frequently queried columns | Donβt over-index β it affects write performance |
Use AUTO INCREMENT for identity | Avoid 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 :