Understanding MySQL Indexes: INDEX vs. PRIMARY KEY vs. UNIQUE vs. FULLTEXT
Here's a table summarizing the key differences:
Type | Uniqueness | Enforces Data Integrity | Additional Features |
---|---|---|---|
INDEX | No | No | Improves query performance |
UNIQUE KEY | Yes (for combinations of indexed columns) | Yes | Enforces unique data |
PRIMARY KEY | Yes (for all columns) | Yes | Main table identifier, often used for physical storage |
FULLTEXT | No (for entire text) | No | Enables full-text search |
CREATE TABLE products (
product_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
category_id INT NOT NULL,
INDEX(category_id) -- Index on category_id column
);
This code creates a table named "products" with an index on the "category_id" column. This will improve query performance when searching for products based on their category.
UNIQUE KEY:
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE, -- Unique key on username
email VARCHAR(100) NOT NULL UNIQUE -- Unique key on email
);
This code creates a table named "users" with unique keys on both "username" and "email" columns. This ensures no duplicate usernames or email addresses exist in the table.
PRIMARY KEY (already shown in example 1):
The PRIMARY KEY definition was included in the first example. It's a special type of UNIQUE KEY that acts as the main identifier for each row.
FULLTEXT:
CREATE TABLE articles (
article_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT FULLTEXT,
content TEXT FULLTEXT -- Fulltext index on content column
);
This code creates a table named "articles" with a full-text index on the "content" column. This allows you to search for keywords within the article content.
It's important to note that these approaches have their own advantages and disadvantages. They might not always be suitable replacements for proper indexing, and the best approach depends on your specific database schema and query patterns.
Here's a quick comparison:
Method | Advantages | Disadvantages |
---|---|---|
Denormalization | Faster queries | Data redundancy, potential inconsistency |
Materialized Views | Faster complex queries | Requires maintenance, additional storage |
Partitioning | Faster queries for specific data ranges | Increased complexity |
Caching | Faster response times | Requires invalidation strategy, external layer management |
mysql indexing key