Using Window Functions with DATEDIFF() to Calculate Moving Averages of Durations in SQL Server

SQL Server’s window functions allow you to perform calculations across sets of rows that are related to the current row, without collapsing those rows into a single result like traditional GROUP BY aggregates would. When combined with the DATEDIFF() function, they can open up many options for analyzing temporal patterns in your data.

Moving averages smooth out short-term fluctuations to reveal longer-term trends in your data. Unlike a simple overall average that treats all historical data equally, a moving average focuses on a sliding window of recent events. This can be quite relevant when analyzing process durations, response times, or any time-based metric where you want to understand current performance trends without being overly influenced by distant historical data.

Read more

SQL Server UNPIVOT Explained

Sometimes you need to do the reverse of pivoting – take data that’s spread across multiple columns and convert it back into rows. You might receive data in a wide format from Excel, need to normalize denormalized data for storage, or simply need to reshape data for a different type of analysis. Fortunately, SQL Server has the UNPIVOT operator which is designed for this very scenario.

Whereas PIVOT transforms rows into columns, UNPIVOT transforms column headers back into row values. This creates a narrower, longer dataset from a wide one.

Read more

How to Enable Query Store in SQL Server

Query Store is SQL Server’s built-in query performance tracking system that captures execution history, plans, and runtime statistics. From SQL Server 2022 it’s enabled by default for all newly created databases. But in earlier versions, it’s disabled by default, which means you’ll need to explicitly enable it on each database where you want to track query performance.

Read more

What is Parameter Sniffing in SQL Server?

Parameter sniffing is a feature in SQL Server where the query optimizer examines (or “sniffs”) the parameter values the first time a stored procedure or parameterized query executes. It uses these specific values to create an execution plan optimized for those particular parameters. The plan is then cached and reused for subsequent executions, even when different parameter values are passed in.

This behavior can be efficient if the initial parameters are representative of typical queries, but it can also cause performance problems if later calls use very different parameter values that make the cached plan inefficient. 

Read more

How PIVOT Works in SQL Server

In SQL databases, a pivot operation transforms rows into columns, making it easier to summarize or compare data across categories. It’s commonly used to convert long, vertical datasets into a wider, more readable format. For example, turning a list of monthly sales records into a table where each month becomes its own column.

By applying aggregation functions like SUM(), COUNT(), or AVG() during the pivot, SQL can reorganize and summarize data for reporting or analysis.

In this article, we’ll take a look at SQL Server’s PIVOT operator, which is designed specifically for pivot operations.

Read more

What is the Query Store in SQL Server?

Query Store is SQL Server’s built-in query performance tracking system. It captures a history of queries, their execution plans, and runtime statistics, storing everything in the database itself. It constantly records what’s happening so you can analyze performance issues after the fact.

Query performance issues can be notoriously hard to debug. A query runs fine for weeks, then suddenly it’s slow, and by the time you check, the problem has vanished or the execution plan is no longer in cache. SQL Server 2016 introduced Query Store to address this. Once enabled on a database, it continuously records query execution history, giving you the data you need to investigate performance problems after they happen. It won’t tell you what’s wrong or how to fix it, but at least you’ll have evidence to work with instead of flying blind.

Read more

Using DATEDIFF() with Window Aggregate Functions to Calculate Time from Event Baselines in SQL Server

When you combine SQL Server’s aggregate functions like MIN() and MAX() with the OVER clause, you can use them as window functions that calculate across partitions while still maintaining individual row data. When combined with DATEDIFF(), it lets you calculate how much time has elapsed from a baseline date within each partition. This can be useful for doing stuff like measuring durations from the start of a process, tracking time since the first event in a group, or calculating age from an initial reference point.

The main advantage of using MIN() or MAX() as a window function is that you can compare every row in a partition against the earliest or latest date in that same partition without needing a self-join or subquery. Each row gets access to the aggregate value while still maintaining its individual row data.

Read more