Changing data type from date to date/time in MySQL?


To change data type from date to date/time, use alter command.

alter table yourTableName change yourColumnName yourColumnName datetime;

Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   LoginDate date
   );
Query OK, 0 rows affected (1.26 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(LoginDate) values('2019-01-21');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(LoginDate) values('2018-05-01');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(LoginDate) values('2017-12-31');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+------------+
| Id | LoginDate  |
+----+------------+
| 1  | 2019-01-21 |
| 2  | 2018-05-01 |
| 3  | 2017-12-31 |
+----+------------+
3 rows in set (0.66 sec)

Following is the query to change data type from date to date/time in MySQL −

mysql> alter table DemoTable change LoginDate LoginDate datetime;
Query OK, 3 rows affected (1.63 sec)
Records : 3 Duplicates : 0 Warnings : 0

Let us check the table description using desc command −

mysql> desc DemoTable;

Output

+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| Id        | int(11)  | NO   | PRI | NULL    | auto_increment |
| LoginDate | datetime | YES  |     | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
2 rows in set (0.19 sec)
raja
Published on 13-Jun-2019 11:23:55
Advertisements