Mysql how to fill missing dates in range?
Fill missing dates with a recursive CTE in MySQL 8.0+. Just grab your cup☕ and try this query:
Plug in your start and end dates, and voilà! A complete date series without a calendar table. Efficient, right?
How to use the generated dates?
Once you've got your date series ready, you probably want to merge your existing data with it. We'll do a LEFT JOIN like this:
Now, every date gets a score. Dates without data? They get a participation trophy of 0.
But what about MySQL below 8.0?
Okay, what if you can't use MySQL 8.0 or its fancy CTEs? Well, we'll use the reliable old numbers table idea. Here's the code:
Yes, it looks like a Chris Nolan plot, but bear with me. Use this to generate a series of dates then wrap it in a LEFT JOIN
and add some COALESCE
for good measure.
What if I need to maintain last 30 days' data?
Now, you may find yourself needing to keep a window of the last 30 days. Kit yourself out with this snazzy MySQL event:
Don't forget to switch ON
the event scheduler, or it’ll be lazier than a sloth on Sunday:
Gives new meaning to "spring cleaning," right?
What about other ranges?
Maybe you need ranges other than dates, like 15-minute slots? We got you:
This generates 15-minute time slots within a single day. Replace 15 MINUTE
with your desired interval.
Making your data presentation-worthy
Sorting your final output by date makes visualisation much easier:
Was this article helpful?