Date Trunc SQL

Galaxy Glossary

How do you truncate a date to a specific part, like the year or month?

The `DATE_TRUNC` function in SQL is used to truncate a date to a specific level of granularity, such as year, month, day, hour, minute, or second. This is useful for grouping and analyzing data by these time intervals.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `DATE_TRUNC` function is a powerful tool for date manipulation in SQL. It allows you to extract a specific part of a date and discard the rest. This is crucial for tasks like reporting, data analysis, and creating summaries. For example, you might want to group sales figures by month to understand trends. `DATE_TRUNC` makes this process straightforward. It's important to note that `DATE_TRUNC` doesn't change the underlying date value; it just extracts a portion of it for comparison or grouping purposes. This function is widely supported across various SQL dialects, including PostgreSQL, MySQL, and SQL Server, although the exact syntax might vary slightly. Understanding the different truncation levels is key to effectively using this function. For instance, truncating to the year will discard the month, day, hour, minute, and second, leaving only the year.

Why Date Trunc SQL is important

The `DATE_TRUNC` function is essential for data aggregation and analysis. It allows you to group data by meaningful time intervals, which is crucial for understanding trends, patterns, and insights from your data. This function simplifies complex date manipulation tasks, making your SQL queries more efficient and readable.

Example Usage


-- Sample table
CREATE TABLE sales (
    sale_id INT PRIMARY KEY,
    sale_date DATE
);

INSERT INTO sales (sale_id, sale_date) VALUES
(1, '2023-10-26'),
(2, '2023-10-27'),
(3, '2023-11-15'),
(4, '2023-11-15'),
(5, '2023-11-16');

-- Truncate to the year
SELECT EXTRACT(YEAR FROM sale_date) AS sale_year, SUM(sale_id) AS total_sales
FROM sales
GROUP BY sale_year;

-- Truncate to the month
SELECT DATE_TRUNC('month', sale_date) AS sale_month, SUM(sale_id) AS total_sales
FROM sales
GROUP BY sale_month;

-- Truncate to the day
SELECT DATE_TRUNC('day', sale_date) AS sale_day, SUM(sale_id) AS total_sales
FROM sales
GROUP BY sale_day;

-- Clean up
DROP TABLE sales;

Common Mistakes

Want to learn about other SQL terms?