What is the performance cost of using PIVOT in Microsoft SQL Server

RajeshKumar Tuta 0 Reputation points
2025-05-14T15:07:42.86+00:00

I'm using PIVOT in my query, but it's resulting in high logical reads and performance degradation. Could you recommend a more optimal alternative approach.

SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
197 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,476 Reputation points Volunteer Moderator
    2025-05-14T15:41:04+00:00

    the pivot does not add a high performance. its just an sum of grouped rows. the cost is the cost of the grouping and any filtering by the where clause. with the correct index, its a single seek with sequential read. without a proper index can be a full database scan, sort, and then read.


  2. Erland Sommarskog 121.3K Reputation points MVP Volunteer Moderator
    2025-05-14T20:39:00.74+00:00

    I concur with Bruce. PIVOT as such does not incur a particular performance overhead.

    Take a query like this one:

    SELECT P.ProductName, Cy.CountryName, SUM(OD.Amount) AS Amount
    FROM   [Order Details] OD 
    JOIN   Products P   ON P.ProductID    = OD.ProductID
    JOIN   Orders O     ON OD.OrderID     = O.OrderID
    JOIN   Customers C  ON C.CustomerID   = O.CustomerID
    JOIN   Countries Cy ON Cy.CountryCode = C.CountryCode
    GROUP  BY P.ProductName, Cy.CountryName
    ORDER  BY P.ProductName, Cy.CountryName;
    

    This query has to scan large tables from start to end (since there is no WHERE clause), so it is certainly expensive.

    If you now decide to pivot this result so that you get one column per country, that is a bit of rearrangement, but the overhead is limited. The big cost is scanning the tables.

    It is someone different if you build a dynamic pivot, since this requires an initial step where you scan the data to find all countries. And if the column you are to pivot by is not indexed, this is one more full scan of the table. However, there are some mitigating factors:

    1. You only have to scan one table, and in this example that may be the Customers table which is a lot smaller than Orders and Order Details.
    2. The column you are pivoting by is often indexed, making the scan cheaper, as only the narrow index has to be scanned.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.