Reshaping Data with PIVOT and UNPIVOT, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 11.5 Free with a free account

Reshaping Data with PIVOT and UNPIVOT

Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.5 · lesson 68 of 7610 min · free with a free account

← Inserting Across Multiple Tables: Techniques and ExamplesNext lesson: Regular Expressions Across Platforms — MySQL and SQL Server Implementation Compared →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Turn rows into columns and back with PIVOT, UNPIVOT and CASE.

  • Build a cross-tab report with CASE expressions inside aggregates
  • Read SQL Server PIVOT syntax and choose a narrow source query
  • Unpivot wide columns with UNPIVOT or UNION ALL and control null cells
  • Explain why unpivoting cannot recover detail lost to aggregation

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,184 words). Read along, or search it.

Opening Scenario

Quarterly Sales Side by Side

Maya Rao, Lantern Books' owner, wants quarterly sales beside each other. Her transaction-style report instead repeats the product name on every observation. Leo Park, the developer, can reshape that report. But if he adds several observations into one cell, can unpivoting recover the individual observations afterward? We'll build a cross-tab from an illustrative product report, then turn its columns back into rows. Watch what happens to missing values and detail.

Long Format

Six Observations, One per Row

This disposable report extension uses two familiar products, with invented quarter amounts. It does not replace the shared bookstore's original orders. The long form stores one observation per row. Database Basics has two first-quarter observations, while Notebook has no third-quarter observation. Long form is convenient for filtering, grouping, and joining on quarter. Adding another quarter adds rows, without adding a new storage column. Run the setup and inspect these six observations. We will keep the two first-quarter observations separate until the aggregation step. The repeated product and quarter are meaningful observations. Treating them as accidental duplicate records would change the amount that the report should total.

Conditional Aggregation

SUM With CASE Builds a Cross-Tab

Conditional aggregation combines case with an aggregate. Group by makes one group per product, and each case selects the amounts for one quarter. Case without else produces null when its condition does not match. Sum ignores those nulls, so each output column totals only its own quarter. This produces a wide cross-tab: products down the side, quarters across the top. MySQL, SQL Server, and SQLite can all express this portable pattern. Run the aggregation. The shell's null display setting prints the word null explicitly, so an absent value cannot be mistaken for an empty label. Database Basics has fifty in the first quarter. Notebook's missing third quarter is null, because that column's aggregate received no non-null amounts.

Zero Versus Missing

Displaying Zero and Counting Matches

Coalesce can display zero for a missing-quarter sum. Decide whether that display choice matches the report's meaning; missing observations and measured zero are different facts. To count observations, put a case inside count. It returns one for a matching quarter and null otherwise, so count includes only matching observations. Avoid else zero inside that count expression. Zero is non-null, so count would include the nonmatching rows as well. Run the display-and-count query. We ask for a third-quarter amount and a first-quarter observation count, which measure different things. Database Basics has two first-quarter events, while Notebook has one. Notebook's third-quarter display becomes zero, but the original missing observation has not been invented.

Quick Check

Building One First-Quarter Cell

A fresh report has first-quarter amounts of three and eight, plus a second-quarter amount of four. The query builds just its first-quarter cell. Which amount appears in that cell? Choose three, fifteen, or eleven. Pause, and calculate from the case condition. Eleven units appear. Both first-quarter amounts contribute, while the second-quarter amount becomes null inside this case expression. Run the new aggregation. Its single output cell summarizes two observations, rather than choosing one of them. The result is eleven. Three would omit a matching observation, while fifteen would include the second quarter and ignore the case filter.

SQL Server PIVOT

Source Query, Aggregate and IN List

SQL Server also offers pivot syntax. Read the source query first: it supplies the row label, the future column label, and the amount to aggregate. Sum fills each intersection, and the in list fixes the quarter headings. The result needs its alias; COUNT(*) is not a valid pivot aggregate. Keep the source narrow. An extra sale identifier becomes another grouping column, splitting observations that you intended to combine into one product row. A new quarter needs another listed heading, controlled dynamic SQL, or a reporting-tool pivot. Unlisted categories have no output column, though grouping identities can still remain.

Wide Report

Saving the Cross-Tab as a Table

Save the aggregate as a separate wide report. It has one column per selected quarter, which suits a spreadsheet export or a side-by-side comparison. This is a derived reporting shape, not a replacement for the long observations. Its first-quarter sum no longer records how many individual contributions produced it. Native pivot and unpivot are not available in MySQL. Conditional aggregation and union all supply the same basic reshaping tools, with explicit null choices. Run the wide-table creation. Its cells now provide the input for our columns-to-rows transformation. The wide report has two product rows. To analyze quarter as a value again, we must turn each named quarter column into a labeled row.

UNPIVOT

Turning Quarter Columns Back Into Rows

Unpivot turns column headings into values in a quarter column. Each populated quarter cell becomes a product-quarter-amount row. SQL Server's native unpivot drops null-valued cells. Its listed input columns must have compatible types, including relevant length details. Unpivot cannot split an aggregate back into its original events. The two first-quarter contributions already became one total, and their separate identities are gone.

Portable Unpivot

One SELECT per Column With UNION ALL

The portable alternative writes one select per wide column. A literal quarter label records which column supplied each value. Union all stacks the branch results without removing repeated complete rows. Unlike native unpivot, this version retains a row for a null-valued cell. That difference matters for exports that must show absent measurements explicitly. Choose whether absence should remain represented, rather than accepting the tool's default silently. Run the stacked version. Each of two products contributes one row for every selected quarter, even when a cell is missing. Six rows appear, including Notebook's null third quarter. Native unpivot would return five rows from these same wide cells.

Null Policy

Filter Each Branch on Its Own Column

To match native unpivot's null behavior, filter each branch on the value that branch exports. The first branch tests first quarter, and the second tests second quarter. The third branch tests third quarter. Testing third quarter in every branch erases valid amounts in other quarters, whenever the third quarter is missing. These filters remove missing cells, not zero-valued cells. A zero can be a real measurement and should remain unless the report explicitly excludes it. Run the filtered version. The predicates now implement a clear policy, while the output remains in long form for further analysis. Five rows remain. The null cell disappears, and every recorded quarter amount survives; none of the original individual observations can be recovered from their sums.

Final Check

COUNT Keeps a Recorded Zero

A new wide report has three cells: zero, null, and seven. This query counts recorded values, rather than adding their amounts. How many cells does count include? Pause, and predict whether a zero is treated like a missing value. Two cells are present. Zero and seven are non-null values, while the null cell is excluded by count of the amount column. Run the new cell query. It demonstrates why a null-removal policy should use is not null, rather than testing whether the amount is positive. The count is two. Counting one would lose a recorded zero; counting three would include the missing value as though it had been measured.

Key Takeaways

Reshaping Cannot Restore Lost Detail

Maya gets quarters side by side, while Leo keeps the original events in long form. Wide reports improve presentation; long observations support flexible storage and analysis. Case with aggregates is a portable pivot. Native pivot needs controlled headings and a carefully chosen source, so unintended grouping columns do not split the totals. Unpivot and union all differ on null cells. Apply the intended policy explicitly, and remember that reshaping cannot restore detail already lost through aggregation.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Reshaping Data with PIVOT and UNPIVOT

How do you pivot rows into columns in MySQL?
MySQL has no PIVOT operator, so use conditional aggregation: group by the row label and put a CASE expression inside an aggregate for each new column. For example, SELECT product, SUM(CASE WHEN quarter = 'Q1' THEN amount END) AS q1, SUM(CASE WHEN quarter = 'Q2' THEN amount END) AS q2 FROM sales GROUP BY product; works in MySQL, SQL Server and SQLite. A quarter with no rows shows NULL unless COALESCE displays zero.
How does the PIVOT operator work in SQL Server?
PIVOT turns the values of one column into column headings and aggregates a measure at each intersection. You supply a source query with the row label, the heading column and the amount, then write PIVOT (SUM(amount) FOR quarter IN ([Q1], [Q2], [Q3])) AS p. Every heading must be listed, and COUNT(*) is not allowed. Keep the source narrow, because any extra column, such as a sale id, becomes another grouping column and splits the totals.
Does UNPIVOT keep NULL values?
No, SQL Server's UNPIVOT drops NULL cells, so a wide table with one empty cell out of six returns five rows. The portable alternative writes one SELECT per wide column with a literal label and stacks them with UNION ALL, which keeps a row for the NULL cell. To match UNPIVOT, filter each branch on its own column with IS NOT NULL; testing amount > 0 instead would also drop real zero values.
Can UNPIVOT reverse a PIVOT?
Only partly: UNPIVOT turns columns back into rows, but it cannot recover individual rows that were aggregated during the pivot. If two first-quarter sales of 20 and 30 became one cell of 50, unpivoting returns a single row of 50, and the separate sales are gone. Keep the original long-format data for filtering, grouping and analysis, and treat the wide table as a derived report for display or export.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →