Calculating... until our next FREE Code-Along Session. Secure your spot now

SQL Insert Timestamp: Quick & Easy Explanation

Ryan Forrester
Jun 24th, 2024
Blog

In this guide, we’ll walk through everything you need to know about timestamps in SQL. We’ll cover:

  • What SQL timestamps are and why they’re useful
  • The different types of timestamp data you can use
  • How to set up tables with timestamp columns
  • Some best practices for working with timestamps

By the time we’re done, you’ll be a pro at handling time-related data in your SQL databases. Let’s dive in!


1. SQL Insert Timestamp Basics

In SQL, a timestamp is a data type that stores both date and time information. Here are the key timestamp-related data types you’ll encounter:

  • TIMESTAMP: Stores date and time with high precision
  • DATETIME: Similar to TIMESTAMP but with some key differences
  • DATE: For when you only need to store the date
  • TIME: For storing just the time of day

Each of these SQL timestamp types has its own use cases, which we’ll explore in depth throughout this guide.


When Would You Insert Timestamps?

Tracking Record Creation and Modification: Timestamps help you know when a record was created or last modified, which is essential for audit trails and version control.

Logging Events: In applications where logging is crucial, such as error tracking or activity logs, timestamps provide a clear record of when each event occurred.

Scheduling and Time Management: Applications that involve scheduling, such as booking systems or project management tools, rely on accurate timestamp data to function correctly.


2. Creating Tables with Timestamp Columns

In this section, we’ll dive into creating tables that include timestamp columns in SQL. Timestamps are crucial for tracking when records are created or updated, and they provide valuable insights into the data’s history and changes. We’ll cover the SQL syntax for adding timestamp columns and explain the different configurations you can use.

Basic Table Creation

To create a table with timestamp columns, you’ll need to use the appropriate data type, such as TIMESTAMP or DATETIME. Here’s an example of how to create a table with both a creation timestamp and an update timestamp:

CREATE TABLE example_table (
    id INT PRIMARY KEY,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

In this example:

  • id: A primary key with auto-increment.
  • product_name: A column to store the product name.
  • quantity: A column to store the quantity sold.
  • price: A column to store the price of the product.
  • created_at: A timestamp column that automatically sets to the current timestamp when the record is created.
  • updated_at: A timestamp column that sets to the current timestamp when the record is created and updates to the current timestamp whenever the record is modified.

Explanation

  1. TIMESTAMP Data Type: The TIMESTAMP data type stores both date and time information. It is highly precise and automatically updates based on certain conditions.
  2. DEFAULT CURRENT_TIMESTAMP: This clause sets the default value of the column to the current timestamp at the time the record is created.
  3. ON UPDATE CURRENT_TIMESTAMP: This clause automatically updates the column to the current timestamp whenever the record is modified.

Configuring Different Timestamp Columns

Depending on your requirements, you might need different configurations for your timestamp columns. Here are a few variations:

Single Timestamp for Creation Only:

CREATE TABLE user_sessions (
    session_id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    session_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This configuration is useful for tracking the start time of user sessions without worrying about updates.

Separate Columns for Date and Time:

CREATE TABLE appointments (
    appointment_id INT PRIMARY KEY AUTO_INCREMENT,
    appointment_date DATE,
    appointment_time TIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This approach separates the date and time into different columns, which can be useful for applications that need to handle them independently.

Using DATETIME Instead of TIMESTAMP:

CREATE TABLE orders (
    order_id INT PRIMARY KEY AUTO_INCREMENT,
    order_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

DATETIME is similar to TIMESTAMP but does not automatically adjust for time zone changes.


Why Choose Five for Managing Timestamps in SQL?

Integrating Five with your SQL operations, especially for managing timestamps, offers a powerful and efficient solution for developing modern, data-driven business applications. Five is designed to simplify database management and web application development, making it accessible to even junior developers. Here’s why you should consider using Five for handling your SQL timestamps alongside your other development needs:

Key Features of Five:

Build: Develop applications locally at no cost with Five’s full-featured environment. This allows you to experiment and refine your database structures, including timestamp configurations, without any initial investment.

Deploy: Deploy applications to a secure and scalable cloud infrastructure. Five makes it easy to manage your applications in a production environment, ensuring high availability and security for your data.

Working with SQL in Five

Five provides an easy environment to work with SQL databases, offering both visual and coding tools to suit your preferences. Here’s how Five can help you manage timestamps efficiently:

Create a MySQL Database Visually

Five.Co - Database Modeler - Manage Databases Visually

With Five’s visual database builder, you can create tables, define fields, set primary and foreign keys, and establish relationships with just a few clicks.

Five.Co - Code Editor

Five’s SQL editor allows you to write SELECT, JOIN, and UPDATE statements directly or use its visual query builder. This flexibility ensures you can perform any database operation efficiently, whether you prefer coding or visual tools.

“The only way to learn a new programming language is by writing programs in it.” – Dennis Ritchie, Creator of the C Programming Language. We’d go even further and say that the best way to learn is by building a real and functional application, and Five makes this possible.


Go From SQL Database to Web App
Start Developing




Practical Example

Let’s say you run an online store and want to track your sales. You need to know when each sale was made and when any changes were made to the sale record. Here’s how you could set up your table:

CREATE TABLE online_sales (
    sale_id INT PRIMARY KEY AUTO_INCREMENT,
    product_id INT,
    quantity_sold INT,
    sale_price DECIMAL(10, 2),
    sale_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

With this table structure:

  • Each sale record is uniquely identified by sale_id.
  • The sale_date column automatically captures the date and time of the sale.
  • The last_modified column updates automatically whenever any changes are made to the record, providing an accurate audit trail.

In the next section, we will explore how to insert timestamp data into your tables effectively.


3. Inserting Timestamps into Tables

Inserting timestamps into tables is a crucial part of managing your database records. Timestamps can be inserted automatically using SQL functions or manually for specific data entries. This section will cover both methods: using CURRENT_TIMESTAMP for automatic insertion and inserting explicit timestamps manually.

Using CURRENT_TIMESTAMP

The CURRENT_TIMESTAMP function is a convenient way to automatically insert the current date and time into a timestamp column. This is useful for tracking when records are created or updated without having to manually enter the date and time each time.

Example: Automatic Insertion with CURRENT_TIMESTAMP

Let’s revisit the sales_records table from the previous section. When inserting a new record, the created_at and updated_at columns will automatically set to the current timestamp.

INSERT INTO sales_records (product_name, quantity, price) 
VALUES ('Product A', 10, 29.99);

In this example:

  • The created_at column automatically captures the timestamp when the record is inserted.
  • The updated_at column also captures the current timestamp and will update automatically whenever the record is modified.

Explanation:

  • The DEFAULT CURRENT_TIMESTAMP clause ensures that the created_at column records the current time at the moment of insertion.
  • The ON UPDATE CURRENT_TIMESTAMP clause updates the updated_at column to the current time whenever the record is updated.

Using Explicit Timestamps

In some cases, you might need to insert specific timestamps into your tables rather than using the current timestamp. This is useful for backdating entries or importing data with historical timestamps.

Example: Manual Insertion of Specific Timestamps

Suppose you need to insert a record with a specific creation time and update time into the sales_records table.

INSERT INTO sales_records (product_name, quantity, price, created_at, updated_at) 
VALUES ('Product B', 5, 49.99, '2024-06-24 12:34:56', '2024-06-24 12:34:56');

In this example:

  • Both created_at and updated_at are set to ‘2024-06-24 12:34:56’.

Explanation:

  • Manually entering the timestamp values allows you to specify exact dates and times for record creation and updates.

Updating Timestamps

Timestamps can also be updated when records are modified. SQL provides mechanisms to automatically update timestamps using the ON UPDATE CURRENT_TIMESTAMP clause or manually by setting the timestamp explicitly.

Example: Automatic Update of updated_at Column

The updated_at column in the sales_records table will automatically update to the current timestamp whenever the record is modified.

UPDATE sales_records 
SET price = 24.99 
WHERE product_name = 'Product A';

In this example:

  • The updated_at column automatically updates to the current timestamp because of the ON UPDATE CURRENT_TIMESTAMP clause.

Example: Manual Update of Timestamps

You can also manually set the updated_at column to a specific timestamp when updating a record.

UPDATE sales_records 
SET price = 24.99, updated_at = '2024-06-25 10:00:00' 
WHERE product_name = 'Product B';

In this example:

  • The updated_at column is manually set to ‘2024-06-25 10:00:00’.

Practical Scenarios

Scenario 1: Tracking Order Dates

For an e-commerce application, it’s important to track when orders are placed and when they are shipped. Here’s how you can manage these timestamps.

Creating the Orders Table:

CREATE TABLE orders (
    order_id INT PRIMARY KEY AUTO_INCREMENT,
    customer_id INT,
    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    shipped_date TIMESTAMP
);

Inserting Orders:

INSERT INTO orders (customer_id, order_date, shipped_date) 
VALUES (123, CURRENT_TIMESTAMP, NULL);

Updating Shipped Date:

UPDATE orders 
SET shipped_date = '2024-06-26 15:00:00' 
WHERE order_id = 1;

Scenario 2: Logging User Activity

For a web application, logging user activity with precise timestamps can help monitor user behavior and system performance.

Creating the Activity Log Table:

CREATE TABLE activity_log (
    log_id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    activity VARCHAR(255),
    activity_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Inserting Activity Logs:

INSERT INTO activity_log (user_id, activity) 
VALUES (456, 'User logged in');

Querying Recent Activities:

SELECT * FROM activity_log 
WHERE activity_timestamp > '2024-06-24 00:00:00';

Inserting timestamps into your SQL tables, whether automatically using CURRENT_TIMESTAMP or manually for specific records, is essential for accurate data tracking and management.


Start developing your first application!

Get Started For Free Today

Sign Up Free Book a demo
Develop your first application with Five now. Start Free

Thank you for your message!

Our friendly staff will contact you shortly.

CLOSE