Closed adnjoo closed 1 month ago
An index in a database is a special data structure that improves the speed of data retrieval operations. It works similarly to an index in a book, allowing the database to quickly locate rows in a table without having to scan through every row. In relational databases, indexes can be applied to one or more columns in a table.
Indexes are primarily used to:
UNIQUE
indexes, they enforce that no two rows have the same value for a specific column.Regular Index: A non-unique index that helps speed up data retrieval but allows duplicate values in the indexed column.
Example:
add_index :users, :email
Unique Index: An index that not only improves performance but also enforces that all values in the indexed column must be unique.
Example:
add_index :users, :username, unique: true
This would prevent two users from having the same username
in the table.
When you create an index on a column (e.g., username
), the database stores a copy of that column's data in a sorted order (or using a different structure like a B-tree). When you query the database, instead of scanning all rows, the database can use the index to quickly jump to the relevant rows.
SELECT
queries) much faster.INSERT
, UPDATE
, and DELETE
operations because the index itself needs to be updated whenever data is modified.In your case, you want the username
to be unique. This means you want an index to ensure fast lookups and also enforce uniqueness, which prevents duplicate usernames.
The migration:
add_index :users, :username, unique: true
creates a unique index, ensuring that no two users can have the same username
while also improving query performance when looking up users by username.
Without an index, the database would perform a full table scan to find records. For example, when querying by username
, it would have to check each row in the users
table, which can be slow for large datasets.
Let me know if this clarifies things or if you need more details!
79
TODO
unique
index