I want to understand how index is created in MySQL – meaning if its a TimeStamp
field – will it create a hash of the TimeStamp
field and store it or just store the literal Value of the timestamp. Since timestamp has a precision of milliseconds – each index will be unique, then how effectively the index creation is done ? Any internals that will help me understand this ?
2
Answers
When you create an index on a TIMESTAMP field or any other data type, MySQL doesn’t store a hash of the value or the literal value itself as the index key. Instead, it uses a data structure called a B-tree (balanced tree) to organise and store index keys. B-trees are commonly used in databases because they provide efficient ways to search, insert, and delete data.
What is an index key?
An index key is a value or set of values extracted from one or more columns of a database table and used to build an index data structure. The purpose of an index key is to facilitate fast data retrieval and efficient querying of the table’s data. Each index key corresponds to a specific row in the table.
Indexes in databases are like bookmarks that help find rows with certain column values efficiently. Without an index, the database has to search through the entire table, starting from the beginning, to locate the needed rows. This becomes slower as the table gets bigger. But if the table has an index for the specific columns being searched, the database can quickly figure out where to jump to within the data, without scanning everything. This is way faster than reading each row one by one.
Mainly there are two types of index mechanisms in MySQL. They are B-Tree Indexes and Hash Indexes.
B-Tree Index Characteristics
Hash Index Characteristics
Comparison:
Answer
For a TimeStamp field, a B-tree index is generally a better choice than a hash index. B-tree indexes provide efficient support for both range queries and exact match queries. Since timestamps often involve queries for specific time ranges or ordered results, a B-tree index can provide better performance and more flexibility in these scenarios.
When you create an index on a TimeStamp field in MySQL, it uses a B-tree indexing (default indexing mechanism) algorithm. This means that the actual timestamp values are stored in a sorted structure, not their hash.