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

What is a Query Hint?

A query hint is a directive you add to your SQL statement that tells the database optimizer how to execute that query. You’re basically overriding the optimizer’s judgment with your own instructions.

Most of the time, your database’s query optimizer does a pretty solid job figuring out the best execution plan. It analyzes statistics, indexes, and table structures to determine the most efficient path. But sometimes you know better (or at least you think you do) and that’s where query hints can be useful.

Read more

What is Query Optimization?

Query optimization is the process of finding the most efficient way to execute a database query.

When you write a SQL query, you’re basically telling the database what data you want, but the database has to figure out how to actually retrieve it. That’s the main job of the query optimizer. The query optimizer is a dedicated component of the database management system (DBMS) that evaluates various possible execution paths and selects the most efficient one.

But there are also things that we can do to help the query optimizer, such as writing efficient SQL, properly indexing tables, maintaining up-to-date statistics, etc.

Understanding how the optimizer works and knowing how to steer it toward better execution plans is what we mean by query optimization.

Read more

What is a UNION ALL in SQL?

UNION ALL is SQL’s way of combining result sets from multiple queries without worrying about duplicates. If you’ve used UNION before, UNION ALL is its faster, less fussy sibling that keeps every single row from all your queries, even if some rows are identical.

So UNION removes duplicate rows automatically, while UNION ALL keeps everything.

Read more

What is a UNION in SQL?

If you ever find yourself needing to combine the results from multiple SELECT statements into a single result set, UNION is probably going to be the tool for the job. By “UNION“, I mean the UNION operator.

The UNION operator takes the output from two SELECT queries and stacks them on top of each other. It basically merges two lists into one, removing any duplicates along the way.

Read more

How to Pivot Rows to Columns in SQL Server (5 Methods)

Pivoting takes data stored vertically in rows and spreads it horizontally into columns. This is something you’ll likely encounter regularly when building reports or reshaping data for analysis. Basically, you’ve got data stored in rows, and you need to flip it so those row values become column headers. Maybe you’re building a report, maybe you’re feeding data to another system, or maybe the client just wants to see things the other way around.

SQL Server gives you several ways to handle this. Let’s walk through five different approaches, from the dedicated PIVOT operator to more flexible techniques that work when you need extra control.

Read more

Using Window Functions with DATEDIFF() to Calculate Running Time Totals 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 provide a powerful way to analyze temporal patterns in your data.

One potential use case is calculating running totals of time durations. Unlike simple aggregates that give you a single summary value, running totals show you the cumulative duration at each point in a sequence. This can be invaluable for tracking accumulated processing time, measuring cumulative delays, or understanding how total duration builds up over a series of events.

Read more

What is a Subquery?

A subquery is a query nested inside another SQL statement. It’s basically a query within a query. You’re using the results of one SELECT statement to help another SQL statement do its job.

Subqueries let you break down complex problems into smaller, more manageable pieces, making your SQL more readable and often more powerful. The outer query relies on the inner query (the subquery) to provide data, filter results, or perform calculations. Once the subquery executes and returns its results, the outer query uses that information to complete its task.

Read more