乐闻世界logo
搜索文章和话题

How to create timestamp column with default value ' now '?

1个答案

1

To create a timestamp column with a default value of the current time in a database, we can use different syntax based on the database system used (e.g., MySQL, PostgreSQL, SQL Server, etc.). Below are methods for creating such columns in common database systems:

MySQL

In MySQL, you can use the CURRENT_TIMESTAMP function to set the default value. For example, if you are creating a new table, you can define the column as follows:

sql
CREATE TABLE events ( id INT AUTO_INCREMENT, event_name VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) );

In this example, the created_at column automatically uses the timestamp at the time of record creation as the default value.

PostgreSQL

In PostgreSQL, you can use CURRENT_TIMESTAMP similarly to MySQL:

sql
CREATE TABLE events ( id SERIAL PRIMARY KEY, event_name VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );

SQL Server

In SQL Server, you can use the GETDATE() function to get the current time:

sql
CREATE TABLE events ( id INT IDENTITY(1,1) PRIMARY KEY, event_name NVARCHAR(255), created_at DATETIME DEFAULT GETDATE() );

Oracle

Oracle uses SYSDATE to get the current date and time:

sql
CREATE TABLE events ( id NUMBER GENERATED BY DEFAULT AS IDENTITY, event_name NVARCHAR2(255), created_at DATE DEFAULT SYSDATE );

These examples all create a table named events that includes a created_at timestamp column with the default value set to the current time. Thus, whenever a new row is inserted into the table, if no specific value is provided for created_at, the system automatically inserts the current time as the default value. This is very useful for recording the time when events occur.

2024年8月14日 14:10 回复

你的答案