SQL Date Functions for Data Analysis

Day 36 – Date Functions On my first day as a data analyst, my manager asked: "Can you show me all orders from the last 30 days?" I wrote: WHERE order_date = '2024-03-16' and manually counted back. Every day I had to update it. Every weekend it broke. Then I learned: WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) That one line is self-updating. Run it today, tomorrow, next year always shows last 30 days. Date functions are in 90% of real SQL queries. Here are the ones that matter most: Get today: CURDATE() → 2024-04-15. NOW() → includes time. Extract parts: YEAR(date), MONTH(date), DAY(date) → use for GROUP BY month Calculate gaps: DATEDIFF(date1, date2) → days between. TIMESTAMPDIFF(MONTH, d1, d2) → months/years Shift dates: DATE_ADD(date, INTERVAL 30 DAY) → 30 days later. DATE_SUB → go back Format output: DATE_FORMAT(date, '%Y-%m') → 2024-04. Use '%Y-%m' for monthly grouping (year first = sorts correctly!) Day 36 / 60 — SQL for Beginners. Follow for a new concept every day. 🚀 #SQL #LearnSQL #SQLforBeginners #DataAnalytics #TechCareer #DataScience

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories