In this tutorial, we focus on calculating the year-over-year (YoY) growth rate—a key performance indicator (KPI) that measures how a company's sales or other metrics change from one year to the next. Traditionally, you might calculate YoY growth by joining the data table with itself to match each year's sales with the previous year's. While this method is straightforward, it can be verbose and less efficient on large datasets.
Modern SQL provides window functions like LAG() that simplify this calculation into a true one-liner. The LAG() function looks at the previous row in the result set (when ordered by a specific column—in this case, year) and returns its value. By using LAG(), we can directly compute the percentage growth from the previous year to the current year without any self-joins.
This approach not only makes the query more concise but also improves performance by reducing the number of joins required. Whether you're analyzing financial data, monitoring sales trends, or performing any time-series analysis, understanding and implementing YoY growth calculations is essential for accurate business insights.
💡 Pro Tip:
Ensure your data is sorted chronologically by year for accurate calculations.
If the dataset contains missing years, consider handling NULLs appropriately to avoid calculation errors.
By mastering these techniques, you'll enhance your SQL skills and boost your ability to analyze and report on key business metrics quickly and efficiently.
✅ Long Way (Using Self-Join):
SELECT
current.year,
current.sales,
previous.sales AS previous_sales,
((current.sales - previous.sales) * 100.0 / previous.sales) AS YoY_Growth_Percentage
FROM sales_data current
JOIN sales_data previous ON current.year = previous.year + 1;
Explanation:
Self-Join: The query joins the sales_data table with itself, matching the current year's data with the previous year's data.
Calculation: The year-over-year growth is calculated as the percentage change between the current year's sales and the previous year's sales.
✅ Shortcut One-Liner (Using LAG() Window Function):
SELECT
year,
sales,
((sales - LAG(sales) OVER (ORDER BY year)) * 100.0 / LAG(sales) OVER (ORDER BY year)) AS YoY_Growth_Percentage
FROM sales_data;
Explanation:
LAG() Function: This window function retrieves the previous year's sales based on the ordering by the year column.
Calculation: The running YoY growth is computed in one line by subtracting the previous year's sales from the current sales, dividing by the previous year's sales, and multiplying by 100 to get a percentage.
Efficiency: This method is concise and processes the entire dataset in a single pass, making it both efficient and easier to read.