You are currently viewing SQL 1.53 SQL Dates

SQL 1.53 SQL Dates

Dates are crucial in many database applications, especially when dealing with time-sensitive data. Here’s a comprehensive tutorial on SQL Dates:

1. Introduction to SQL Dates:

In SQL, dates are typically represented as data types such as DATE, DATETIME, or TIMESTAMP, depending on the precision required for the application. These data types store date and time information in a structured format, allowing for easy manipulation and comparison.

2. Creating a Sample Table:

Let’s start by creating a sample table to work with. We’ll call it sales_data, which contains information about sales transactions, including a column for the transaction date.

CREATE TABLE sales_data (
    transaction_id INT PRIMARY KEY,
    transaction_date DATE,
    amount DECIMAL(10, 2)

3. Inserting Sample Data:

Now, let’s insert some sample data into our sales_data table.

INSERT INTO sales_data (transaction_id, transaction_date, amount) 
    (1, '2024-05-01', 1000.00),
    (2, '2024-05-10', 1500.00),
    (3, '2024-05-15', 2000.00);

4. Retrieving Data:

a. Retrieve all transactions after a specific date:

SELECT * FROM sales_data
WHERE transaction_date > '2024-05-10';

This query will retrieve all transactions that occurred after May 10, 2024.

b. Retrieve transactions within a specific date range:

SELECT * FROM sales_data
WHERE transaction_date BETWEEN '2024-05-01' AND '2024-05-15';

This query will retrieve transactions that occurred between May 1, 2024, and May 15, 2024.

5. Date Functions:

SQL provides various functions to manipulate and extract information from dates.

a. Extracting Year, Month, and Day:

    EXTRACT(YEAR FROM transaction_date) AS transaction_year,
    EXTRACT(MONTH FROM transaction_date) AS transaction_month,
    EXTRACT(DAY FROM transaction_date) AS transaction_day
FROM sales_data;

This query extracts the year, month, and day components from the transaction_date column.

b. Formatting Dates:

    DATE_FORMAT(transaction_date, '%Y-%m-%d') AS formatted_date
FROM sales_data;

This query formats the transaction_date column in ‘YYYY-MM-DD’ format.

6. Aggregating Data by Date:

You can aggregate data based on date components using SQL’s GROUP BY clause.

    EXTRACT(YEAR FROM transaction_date) AS transaction_year,
    SUM(amount) AS total_sales
FROM sales_data
GROUP BY EXTRACT(YEAR FROM transaction_date);

This query calculates the total sales for each year.


Understanding SQL Dates is essential for managing temporal data effectively in databases. By mastering date manipulation techniques, you can perform various analytical tasks and extract valuable insights from your data. Experiment with different queries and functions to deepen your understanding of SQL Dates.

Leave a Reply