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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Regular Expressions Across Platforms — MySQL and SQL Server Implementation Compared →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
How does the PIVOT operator work in SQL Server?
Does UNPIVOT keep NULL values?
Can UNPIVOT reverse a PIVOT?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →