Calculating Month-Over-Month Growth Rate in SQL

To benchmark your business, you’ll want to compute week-over-week, month-over-month and year-over-year growth rates. In the case of Silota, we are not only interested in the number of charts created monthly, but also their growth rates on a month-to-month basis.

SELECT date_trunc('month', timestamp) as date,
       count(*) as count
FROM events
WHERE event_name = 'Created Chart'
GROUP BY 1
ORDER BY 1
date count
2016-01-01 10
2016-01-02 12
2016-01-03 15
... ...

The above query should give us a neat table with the number of charts created every month. To compute the growth rates, we use window functions and the lag function. First to understand how the lag function works:

SELECT date_trunc('month', timestamp) as date,
       count(*) as count,
       lag(count(*), 1) over timestamp
FROM events
WHERE event_name = 'Created Chart'
GROUP BY 1
ORDER BY 1
date count lag
2016-01-01 10
2016-01-02 12 10
2016-01-03 15 12
... ... ...

The lag function returns a value evaluated at the row that is definable offset before the current row within the partition. In this particular we have simply picked the value from the previous row (offset of 1). To compute growth rates, it’s just a matter of subtracting the current value from the previous value:

SELECT date_trunc('month', timestamp) as Date,
       count(*) as Count,
       100 * (count(*) - lag(count(*), 1) over (order by timestamp)) / lag(count(*), 1) over (order by timestamp)) || '%' as growth
FROM events
WHERE event_name = 'Created Chart'
GROUP BY 1
ORDER BY 1
date count growth
2016-01-01 10
2016-01-02 12 20%
2016-01-03 15 25%
... ... ...

No fuss, just SQL We are open sourcing everything from the experience working with our agency clients. They spend thousands of dollars to get this level of detailed analysis – which you can now get for free. You'll learn bucketing, finding outliers, calculating correlations, budgeting & forecasting, return on spend and investment, data smoothing and cleaning applied to freemium, transactional, advertising, two-sided marketplace and subscription based business models. We send one update every week. Join 400+ data analysts who are leveling up with our recipes. 👊

No spam, ever! Unsubscribe any time.