How to convert columns to rows in SQL using UNPIVOT

This tutorial explores whether UNPIVOT is the most effective way to transpose column data into rows in SQL Server. There are several approaches to switching data between columns and rows. Each method is reviewed individually, and its execution plan is analyzed to evaluate performance.

Timesteps

00:00 Introduction

00:38 Convert data from columns to rows using UNION ALL statements.

01:17 View the execution plan of the query in Query Profiler.

01:37 Transpose columns to rows using the UNPIVOT operator.

01:52 Display the Estimated Execution Plan.

01:57 Rotate columns to rows with the VALUES statement.

02:00 Check the execution plan of the query.

02:05 Use dynamic SQL.

02:26 Execute a dynamic UNPIVOT query with XML.

02:45 Compare the execution plans of the five methods.

03:05 Practical scenario – find the most frequent outcome of the game for each player.

03:12 Detect bottlenecks in the SQL query using Query Profiler.

03:35 Use the VALUES statement.

03:45 Tune the query execution plan – avoid sorting.

03:54 Wrapping up.