Pivoting JSON Data in SQL Server

JSON has become a common format for data exchange, and SQL Server’s built-in JSON support makes it straightforward to work with JSON data directly in your queries. But what happens when you need to pivot JSON data – transforming nested structures or array elements into a columnar format for reporting or analysis?

SQL Server provides functions like OPENJSON(), JSON_VALUE(), and JSON_QUERY() that let you extract and manipulate JSON data. Combined with standard pivoting techniques, you can reshape JSON data into whatever format you need. This can be particularly useful when you’re receiving JSON from APIs, storing semi-structured data, or working with configuration data that doesn’t fit neatly into traditional tables.

Read more

Using Subqueries with SQL Server’s DATEDIFF() Function

While SQL Server’s DATEDIFF() function is relatively straightforward when you’re comparing two known dates, it becomes more flexible when the dates you compare are sourced directly from your tables. Instead of hardcoding dates, you can embed subqueries directly into the DATEDIFF() function to dynamically retrieve the dates you need.

This approach can be especially useful when you’re working with aggregate functions like MIN() and MAX(), or when you need to pull specific dates based on certain conditions. The subqueries execute first, return their date values, and DATEDIFF() uses those results to perform the calculation.

Read more

PIVOT vs GROUP BY in SQL Server

If you’re new to SQL or just starting to explore data transformation techniques, you might be confused about when to use PIVOT versus GROUP BY. They may seem similar at first. After all, both aggregate data, both can summarize information, and both produce condensed result sets. But they serve fundamentally different purposes and produce very different output structures.

Understanding the distinction between these two operations will help you write more effective queries. GROUP BY aggregates data vertically, keeping your results in a row-based format. PIVOT transforms data horizontally, turning row values into column headers. Let’s break down exactly what each does and when you’d use one over the other.

Read more

Dynamic PIVOT in SQL Server for Unknown Column Values

Most pivot operations in SQL tend to use hardcoded column lists. This is where you explicitly specify every column name in the IN clause. That works great when you know exactly which values will appear in your data. But what happens when those values change? When new categories get added, when you’re working with user-generated data, or when you’re building a query that needs to work across different datasets?

That’s when you might want to consider dynamic PIVOT. Instead of hardcoding column names, you query the data to discover what columns you need, build the PIVOT query as a string, and execute it dynamically. It’s more complex than static PIVOT, but it’s pretty much essential when your column values aren’t predetermined.

Read more

Building a Survey Results Dashboard in SQL

Survey data can be messy. You’ve got responses scattered across dozens or hundreds of rows, multiple choice answers, rating scales, and so on. And the challenge of turning all that raw data into something stakeholders can actually understand. A well-designed survey dashboard can transform those individual responses into a grid that shows patterns instantly. For example, which questions are getting strong agreement, where opinions diverge, and what trends emerge across different respondent groups.

Read more

What is a Query Plan Cache?

A query plan cache is an area of a database management system‘s memory that stores compiled execution plans for queries. When you execute a query, the database’s optimizer analyzes the query and creates an execution plan, which is basically a set of instructions for how to retrieve and process the requested data.

But compiling this plan requires computational resources, so database systems cache it in memory for reuse rather than recompiling the same plan repeatedly.

This caching mechanism is a fundamental performance optimization found in virtually all modern relational database systems. By reusing compiled plans, databases avoid the overhead of repeatedly analyzing the same queries, resulting in faster query execution and reduced CPU consumption.

Read more

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 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