Using DATE_TRUNC to Round Dates in PostgreSQL
📖 Scenario: You work in a company that tracks sales data with timestamps. You want to group sales by month to see monthly totals.
🎯 Goal: Build a simple PostgreSQL query that uses DATE_TRUNC to round timestamps to the start of the month.
📋 What You'll Learn
Create a table called
sales with columns id (integer), sale_date (timestamp), and amount (numeric).Insert three sales records with exact timestamps and amounts.
Create a variable or CTE to hold the truncation precision 'month'.
Write a query that selects the truncated
sale_date by month and sums amount grouped by that truncated date.💡 Why This Matters
🌍 Real World
Grouping sales or events by month helps businesses analyze monthly trends and make decisions.
💼 Career
Knowing how to use DATE_TRUNC is useful for data analysts and database developers working with time-series data.
Progress0 / 4 steps