DATE, DATETIME 그리고 TIMESTAMP

출판일자 

읽는 데 걸리는 시간 2분


회사에서 login 관련 User DB 모델링을 하다가 시간 타입을 다룰 일이 생겼다. 기본적으로는 Date 에 대해 알고만 있었지 다른게 뭐 있을지 전혀 몰랐는데! ChatGPT 와 Bard 검색으로 계정이 등록되었을 때 시점을 저장할 ‘created_at”, 어떤 operation 이 일어나면 그 시점을 저장할 ‘updated_at’ 을 추가 해주고 싶었다.

I want to update a field created_at and updated_at inside the table user in SQL I want to change the type of field ‘created_at’ in the table ‘user’ from ‘Date’ to ‘TIMESTAMP’ and want to automatically fill up with the current_timestamp

이런 식으로 점차 검색 스코프를 줄여 ALTER TABLE user MODIFY COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP; ALTER TABLE user MODIFY COLUMN last_logged_in TIMESTAMP AFTER updated_at;

이라는 답을 얻어냈다!

여기서 Date 이외에도 Timestamp 라는 타입이 있는 것을 알게되었고..

https://dev.mysql.com/doc/refman/8.0/en/datetime.html 🔗

에서 MySQL 에서는 Date, DateTime 그리고 TimeStamp 가 있음 을 확인했다.

각 타입은 1. Date : Date ONLY, NO time 2. Timestamp : Date + Time (4byte) (1970.01.01 ~ 2038.01.19) 3. Datetime : Date + Time (8byte) (Timestamp 보다 범위가 큼)

이렇다! 그리고 Timestamp, Datetime 둘다 DEFAULT 로 현재 시간도 들어감도 확인 (Datetime: MySQL >= 5.6)

기본적으로는 Timestamp 를 쓰는게 맞겠다.