adnjoo / dueltasks

Gamify Your Todos 👾
https://dueltasks.com/
MIT License
0 stars 0 forks source link

username #80

Closed adnjoo closed 1 day ago

adnjoo commented 2 days ago

79

Screenshot 2024-10-22 at 11 08 01 PM

TODO

adnjoo commented 2 days 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.

Why Use an Index?

Indexes are primarily used to:

Types of Indexes

  1. 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
  2. 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.

How an Index Works

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.

Trade-offs

Example in Rails

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

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!