Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MySql DATETIME takes 8 Bytes instead of 6 Bytes?

Tags:

database

mysql

MySql DATE is occupying 3 Bytes and TIME is occupying 3 Bytes but DATETIME is taking 8 Bytes. I assume like it should be 6 Bytes (3+3) instead of 8 Bytes. What is the logic behind this and why the extra two bytes are used?

like image 477
Vishnu Y Avatar asked Apr 08 '14 07:04

Vishnu Y


People also ask

How many bytes does a datetime take?

DATETIME: Eight bytes: A four-byte integer for date packed as YYYY×10000 + MM×100 + DD and a four-byte integer for time packed as HH×10000 + MM×100 + SS.

How many bytes is SQL datetime?

The size is fixed at 7 bytes with elements YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND .


1 Answers

According to MySQL internals documentation, it's needed because of specific storage requirements:

+-----------+------------------------+---------------------+
|   YEAR    | 1 byte, little endian  |      Unchanged      |
+-----------+------------------------+---------------------+
|   DATE    | 3 bytes, little endian |      Unchanged      |
+-----------+------------------------+---------------------+
|           |                        | 3 bytes +           |
|   TIME    | 3 bytes, little endian | fractional-seconds  |
|           |                        | storage, big endian |
+-----------+------------------------+---------------------+
|           |                        | 4 bytes +           |
| TIMESTAMP | 4 bytes, little endian | fractional-seconds  |
|           |                        | storage, big endian |
+-----------+------------------------+---------------------+
|           |                        | 5 bytes +           |
| DATETIME  | 8 bytes, little endian | fractional-seconds  |
|           |                        | storage, big endian |
+-----------+------------------------+---------------------+

In particular, DATETIME has 8 bytes:

  • 4 bytes: integer for date represented as YYYY×10000 + MM×100 + DD
  • 4 bytes: integer for time represented as HH×10000 + MM×100 + SS

So it's important to realize, that output representation and storage representation are two very different things. As you can see, structure for datetime is two integers with some internal calculations for both parts - date and time.

like image 103
Alma Do Avatar answered Oct 19 '22 12:10

Alma Do