How to add a “created at” column in a table to set the timestamp in MySQL?


You need to use ALTER command to add a created at column to an already created table in MySQL.

Let us first create a table. The query to create a table is as follows. Here is your table without the “created at” column

mysql> create table formDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Email varchar(128),
   - > PhoneNumber varchar(15),
   - > Country varchar(30),
   - > Platform varchar(40)
   - > );
Query OK, 0 rows affected (0.53 sec)

Now implement the above syntax to add a “created at” column with type timestamp and default with CURRENT_TIMESTAMP.

Note - Keep in mind if you are giving a space between created at then you need to use the backtick symbol.

The following is the query to add a “created at” column for the above table. The “created_at” column is a TIMESTAMP column whose default value is set to CURRENT_TIMESTAMP as you can see in the below query

mysql> alter table formDemo
   - > add column `created at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
Query OK, 0 rows affected (0.42 sec)
Records: 0 Duplicates: 0 Warnings: 0

Now check the description of table once again with the help of DESC command.

The query is as follows

mysql> DESC formDemo;

The following is the output displaying the “created at” column in MySQL

+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| Id          | int(11)      | NO   | PRI | NULL              | auto_increment |
| Email       | varchar(128) | YES  |     | NULL              |                |
| PhoneNumber | varchar(15)  | YES  |     | NULL              |                |
| Country     | varchar(30)  | YES  |     | NULL              |                |
| Platform    | varchar(40)  | YES  |     | NULL              |                |
| created at  | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
+-------------+--------------+------+-----+-------------------+----------------+
6 rows in set (0.01 sec)

Look at the above sample output, the column “created at” has been added successfully.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements