In MySQL database, datetime, bigint, and timestamp are used to represent time selection. Which one is the most efficient for storing time?

In MySQL database, datetime, bigint, and timestamp are used to represent time selection. Which one is the most efficient for storing time?

In the database, datetime, bigint, and timestamp can be used to represent time. So which type is more appropriate to choose to store time?

# Post-data preparation

Insert 50w data into the database through the program

Data Sheet:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `time_date` datetime NOT NULL,
  `time_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `time_long` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `time_long` (`time_long`),
  KEY `time_timestamp` (`time_timestamp`),
  KEY `time_date` (`time_date`)
) ENGINE=InnoDB AUTO_INCREMENT=500003 DEFAULT CHARSET=latin1

Among them, time_long, time_timestamp, and time_date are different storage formats for the same time.

Entity class users

/**
 * @author hetiantian
 * @date 2018/10/21
 * */
@Builder
@Data
public class Users {
    /**
     * Self-incrementing unique id
     * */
    private Long id;

    /**
     * Date type time * */
    private Date timeDate;

    /**
     *Time of timestamp type* */
    private Timestamp timeTimestamp;

    /**
     * Long type time * */
    private long timeLong;
}

DAO layer interface

/**
 * @author hetiantian
 * @date 2018/10/21
 * */
@Mapper
public interface UsersMapper {
    @Insert("insert into users(time_date, time_timestamp, time_long) value(#{timeDate}, #{timeTimestamp}, #{timeLong})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    int saveUsers(Users users);
}

The test class inserts data into the database

public class UsersMapperTest extends BaseTest {
    @Resource
    private UsersMapper usersMapper;

    @Test
    public void test() {
        for (int i = 0; i < 500000; i++) {
            long time = System.currentTimeMillis();
            usersMapper.saveUsers(Users.builder().timeDate(new Date(time)).timeLong(time).timeTimestamp(new Timestamp(time)).build());
        }
    }
}

To generate data code, go to github: https://github.com/TiantianUpup/sql-test/ If you don’t want to use code generation, but want to import data through a sql file, the sql file network disk address is attached at the end of the article.

# SQL query rate test

Query by datetime type:

select count(*) from users where time_date >="2018-10-21 23:32:44" and time_date <="2018-10-21 23:41:22"

Time taken: 0.171

Query by timestamp type

select count(*) from users where time_timestamp >= "2018-10-21 23:32:44" and time_timestamp <="2018-10-21 23:41:22"

Time taken: 0.351

Query by bigint type

select count(*) from users where time_long >=1540135964091 and time_long <=1540136482372

Time taken: 0.130s

Conclusion Under the InnoDB storage engine, the performance of searching by time range is bigint > datetime > timestamp

# SQL group rate test


Using bigint for grouping will group each piece of data. If bigint is converted before grouping, there is no point in comparing. Conversion also takes time.

Group by datetime type:

select time_date, count(*) from users group by time_date

Time taken: 0.176s

Group by timestamp type:

select time_timestamp, count(*) from users group by time_timestamp

Time taken: 0.173s

Conclusion: Under the InnoDB storage engine, by time grouping, the performance of timestamp > datetime, but the difference is not big.

# sql sorting rate test

Sort by datetime type:

select * from users order by time_date

Time taken: 1.038s

Sort by timestamp type

select * from users order by time_timestamp

Time taken: 0.933s

Sort by bigint type

select * from users order by time_long

Time taken: 0.775s

Conclusion: Under the InnoDB storage engine, by time sorting, the performance of bigint > timestamp > datetime

# Summary

If you need to operate on the time field (such as searching or sorting by time range, etc.), it is recommended to use bigint. If the time field does not need any operation, it is recommended to use timestamp. Using 4 bytes to save space is more convenient, but the recorded time is limited to 2038.

The SQL file network disk address in the article: Link: https://pan.baidu.com/s/1cCRCxtTlPriXMERGsbnb_A Extraction code: hbq2

This concludes this article about choosing between datetime, bigint, and timestamp to represent time in MySQL database, and which one is the most efficient for storing time. For more information about database datetime, bigint, and timestamp, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the pitfalls of DTS caused by the timestamp and datetime time zone issues in MySQL
  • The difference and choice between datetime and timestamp in MySQL
  • The difference and usage of datetime and timestamp in MySQL
  • Datetime and Timestamp comparison in Mysql
  • Summary of the use of Datetime and Timestamp in MySQL

<<:  10 Things Excellent Web Developers Must Know to Improve Their Development Skills

>>:  A brief analysis of CSS :is() and :where() coming to browsers soon

Recommend

MySQL MyISAM default storage engine implementation principle

By default, the MyISAM table will generate three ...

Docker data volume common operation code examples

If the developer uses Dockerfile to build the ima...

Detailed process of using nginx to build a webdav file server in Ubuntu

Install nginx Note that you must install nginx-fu...

ReactHooks batch update state and get route parameters example analysis

Table of contents 1. How to update in batches Con...

Solutions to browser interpretation differences in size and width and height in CSS

Let’s look at an example first Copy code The code ...

How to configure SSL for koa2 service

I. Introduction 1: SSL Certificate My domain name...

Tips for implementing multiple borders in CSS

1. Multiple borders[1] Background: box-shadow, ou...

Detailed explanation of CSS sticky positioning position: sticky problem pit

Preface: position:sticky is a new attribute of CS...

Vue implements small notepad function

This article example shares the specific code of ...

A screenshot demo based on canvas in html

Written at the beginning I remember seeing a shar...

CSS3 realizes the graphic falling animation effect

See the effect first Implementation Code <div ...

Detailed explanation of MySQL Truncate usage

Table of contents MySQL Truncate usage 1. Truncat...

Summary of various methods for JavaScript to determine whether it is an array

Table of contents Preface Array.isArray construct...