How to generate data in MySQL?

SQL is notoriously bad at returning data that is not in the database. You can find the beginning and ending values for gaps of dates, but getting all the dates is hard.

The solution is to create a calendar table with one record for each date and OUTER JOIN it to your query.

Here is an example assuming that created_at is type DATE:

SELECT calendar_date, COUNT(`id`)
FROM calendar LEFT OUTER JOIN my_table ON calendar.calendar_date = my_table.created_at
GROUP BY calendar_date

(I’m guessing that created_at is really DATETIME, so you’ll have to do a bit more gymnastics to JOIN the tables).

Leave a Comment