← Power Query for Data Analysis · Lesson 10 of 17

Module Nine

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
1

Course Outline

📊 Certified Power Query for Data Analysis Expert – Module 1

📘 Module One: Welcome to Power Query – Your Data Cleaning Superpower!

Hello, young data explorer! 👋 Have you ever tried to solve a puzzle but the pieces were all mixed up? Or maybe you had a big bag of colourful beads but they were tangled? That’s what messy data looks like. Power Query is a magical tool inside Excel that helps you untangle, clean, and organise data so you can find answers quickly. This module is your first step to becoming a Certified Power Query for Data Analysis Expert. We will learn together using stories, pictures, and lots of fun examples. Ready? Let’s go!

🎯 Learning Objectives

By the end of this module, you will be able to:

  • Explain what Power Query is and why it is useful.
  • Identify messy data and know how to fix it.
  • Connect Power Query to a data source (like a table or a file).
  • Use simple steps to clean, filter, and sort data.
  • Understand the basic "Get & Transform" workflow.
  • Feel confident to start your first data project!

📖 Warm‑up Story: The Great School Bake Sale

At Sunshine Primary School, the PTA decided to have a big bake sale. Everyone brought cakes, cookies, and doughnuts. But the list of who brought what was a mess! ✏️ Some names were spelled wrong (like "Chidi" and "Chidii"), some amounts were missing, and the treats were all mixed up. Mrs. Ade, the teacher, spent hours trying to count everything. Then her nephew, Tunde, said: “Aunty, why don’t you use Power Query? It can clean this in seconds!” Mrs. Ade was amazed. Power Query fixed the spelling, filled in the missing numbers, and even sorted the treats from most to least. The bake sale was a huge success, and Mrs. Ade became the Data Queen of the school! 👑

📚 Main Lessons

Lesson 1: What is Data? (And why is it messy?)

Definition: Data is just information – like numbers, words, or pictures. When data is organised neatly, we call it clean data. When it’s mixed up, it’s messy data.

Why important: If data is messy, we cannot make good decisions. Imagine trying to count your pocket money if all the coins were mixed with buttons!

Simple explanation: Data is like a drawer full of socks. If they are paired and folded, you find what you need. If they are tangled, you waste time.

Real-life example: A shopkeeper uses a list of items sold. If the list has mistakes, he might order too much or too little stock.

School example: Your teacher has a list of students and their test scores. If a name is missing, that student might not get a report card.

Home example: Your family’s grocery list. If it says “milk” twice and “egg” zero, you might end up with too much milk!

Nigerian example: A market woman in Lagos keeps a record of how many yams she sells each day. If she writes “3 yam” one day and “three yams” the next, her totals will be wrong.

Illustration (ASCII):

   Messy data                    Clean data
   ------------                  -----------
   Chidi, 12                     Chidi, 12
   chidii, 12                    Chidi, 12   (fixed)
   ChiDi, 12                     Chidi, 12
   (missing amount)              Chidi, 10   (filled)

Mini summary: Data is information. Messy data is confusing. Power Query helps us make it clean and useful.

Lesson 2: Meet Power Query – Your Data Detective

Definition: Power Query is a tool inside Microsoft Excel (and Power BI) that helps you get data, clean it, and change it into the shape you want.

Why important: It saves hours of manual work. Instead of fixing each mistake by hand, Power Query does it automatically!

Simple explanation: Think of Power Query as a robot that reads your messy data, follows your instructions, and gives you back a neat table.

Real-life example: A bank uses Power Query to combine daily transaction lists from many branches into one clean report.

School example: The librarian uses Power Query to combine book lists from different classrooms into one master list.

Home example: You use it to organise your collection of football cards – sort by team, then by player name.

Nigerian example: A small business owner in Kano uses Power Query to merge sales from her shop, her online store, and her WhatsApp orders.

Illustration (ASCII):

   [ Messy data ]  ➡️  [ POWER QUERY ]  ➡️  [ Clean data ]

Mini summary: Power Query is a smart assistant that turns messy data into neat data.

Lesson 3: The "Get & Transform" Journey

Definition: "Get & Transform" is the name of the Power Query tool in Excel. Get means we bring data in. Transform means we change it to make it better.

Why important: Every data project starts with getting data, and the real magic happens during transformation.

Simple explanation: It’s like going to the market (Get) and then cooking the food (Transform) to make a tasty meal.

Real-life example: A weather scientist gets temperature data from satellites and transforms it into a weather forecast.

School example: Your class gets survey answers (Get) and then sorts them by favourite subject (Transform).

Home example: You get a list of your toys (Get) and then group them by colour (Transform).

Nigerian example: A farmer gets rainfall data from 10 different villages and transforms it into one table to see which village needs more water.

Illustration (ASCII):

   GET                         TRANSFORM
   ⬇️                           ⬇️
   [ Excel table ]  ➡️  [ filter, sort, rename ]  ➡️  [ clean table ]

Mini summary: Get = bring data; Transform = improve data. Together they make Power Query powerful.

Lesson 4: Connecting to a Data Source

Definition: A data source is where your data lives – like an Excel file, a CSV, a database, or even a web page.

Why important: You cannot use Power Query without telling it where to find your data.

Simple explanation: It’s like telling your robot where the box of Lego is, so it can start building.

Real-life example: A doctor connects to a hospital database to get patient records.

School example: You connect to a shared folder where your class project files are saved.

Home example: You connect to a CSV file that has the family budget.

Nigerian example: A teacher connects to the school’s online portal to download the exam scores of all students.

Illustration (ASCII):

   [ Excel file ]  ──┐
   [ CSV file   ]  ──┼──>  Power Query  ──>  [ Clean data ]
   [ Web page   ]  ──┘

Mini summary: Data source is the home of your data. Power Query can connect to many different homes.

Lesson 5: The Power Query Editor Window

Definition: The Power Query Editor is a special window where you can see your data and perform transformation steps.

Why important: This is your control room. Everything you do to clean data happens here.

Simple explanation: It’s like the kitchen where you chop, stir, and cook your data.

Real-life example: A journalist uses the editor to remove duplicate names from a list of interview participants.

School example: You use it to remove empty rows from your science project data.

Home example: You use it to rename columns from “A” and “B” to “Item” and “Price”.

Nigerian example: A bank clerk uses the editor to combine first name and last name columns into one “Full Name” column.

Illustration (ASCII):

   +------------------------------------+
   |  Power Query Editor                 |
   |  [ Table view ]  [ Steps list ]    |
   |  [ Filter ] [ Sort ] [ Add Column ] |
   +------------------------------------+

Mini summary: The editor is where you see and change your data step by step.

Lesson 6: Removing Unwanted Columns

Definition: Columns are the vertical boxes in a table. Sometimes we have too many columns, and we don’t need all of them.

Why important: Fewer columns make our data easier to read and faster to process.

Simple explanation: It’s like taking out the toys you don’t play with from your toy box so you can find your favourite ones quickly.

Real-life example: A school removes the “middle name” column because they only need first and last names.

Home example: You remove the “price per kg” column and keep only “total price”.

Nigerian example: A shop removes the “supplier address” column because they only need the supplier name.

Illustration (ASCII):

   Before:   [ID] [First] [Last] [Address] [Phone] [Email]
   After:    [ID] [First] [Last] [Phone]            (removed Address & Email)

Mini summary: You can delete columns you don’t need to keep your data tidy.

Lesson 7: Filtering Rows (Keeping only what you need)

Definition: Filtering means showing only the rows that meet a condition – like keeping only students with scores above 50.

Why important: It helps you focus on the most important data.

Simple explanation: Like using a strainer to keep the noodles and let the water go.

Real-life example: A shopkeeper filters to see only sales above ₦10,000.

School example: A teacher filters to see only students who passed the exam.

Home example: You filter your movie list to show only cartoons.

Nigerian example: A farmer filters his harvest records to see only the days when he harvested more than 50 yams.

Illustration (ASCII):

   All rows              Filter: Score > 50
   [Chidi, 45]   ➡️      [Ade, 78]
   [Ade, 78]     ➡️      [Bola, 92]
   [Bola, 92]    ➡️      [Tunde, 63]
   [Tunde, 63]   ➡️

Mini summary: Filtering lets you keep only the rows that match your rule.

Lesson 8: Sorting Data (Putting things in order)

Definition: Sorting means arranging rows in a specific order – from A to Z, or from smallest to largest.

Why important: Sorted data is easier to scan and compare.

Simple explanation: Like arranging your books on a shelf by height or by colour.

Real-life example: A teacher sorts students by name to call attendance quickly.

School example: You sort your flashcards from easiest to hardest.

Home example: You sort your clothes by colour before putting them in the wardrobe.

Nigerian example: A market woman sorts her goods by price – cheapest first, so customers can see the deals.

Illustration (ASCII):

   Before:  [Bola, 45] [Ade, 78] [Chidi, 63]
   After (sort by name A→Z): [Ade, 78] [Bola, 45] [Chidi, 63]

Mini summary: Sorting arranges your data in a logical order.

Lesson 9: Changing Data Types (Text, Number, Date)

Definition: Data type tells Power Query what kind of information is in a column – like text (words), numbers, or dates.

Why important: If Power Query thinks a number is text, you cannot add or multiply it. So we must set the right type.

Simple explanation: Like putting toys in the right boxes: Lego in the Lego box, cars in the car box.

Real-life example: A cashier sets the “Price” column to Decimal Number so he can calculate totals.

School example: You set the “Birthday” column to Date so you can sort by age.

Home example: You set the “Number of guests” column to Whole Number.

Nigerian example: A business owner sets the “Sales Amount” to Currency (₦) so it shows the Naira symbol.

Illustration (ASCII):

   Column      Old Type      New Type
   ---------   ---------     ---------
   Name        Text          Text       (stays)
   Age         Text    ➡️    Whole Number
   Salary      Text    ➡️    Currency (₦)

Mini summary: Correct data types help Power Query understand your data correctly.

Lesson 10: Renaming Columns (Giving clear names)

Definition: Renaming means changing the heading of a column to something more meaningful.

Why important: Good names help you and others understand the data easily.

Simple explanation: Like putting a label on a box so you know what’s inside without opening it.

Real-life example: Change “Col1” to “Student Name”.

School example: Change “Marks” to “Test Score”.

Home example: Change “A” to “Day” and “B” to “Activity”.

Nigerian example: Change “AMT” to “Amount Paid (₦)”.

Illustration (ASCII):

   Before:   [ID]  [Fname]  [Lname]  [Score]
   After:    [ID]  [First]  [Last]   [Test Score]

Mini summary: Clear column names make data easy to read.

Lesson 11: Replacing Values (Fixing mistakes)

Definition: Replace means to change one value to another – like changing “N/A” to “0” or “Lagos” to “LAG”.

Why important: It fixes typos and inconsistent entries.

Simple explanation: Like using a correction tape on your notebook to change a wrong word.

Real-life example: Replace “Kg” with “kg” to make it uniform.

School example: Replace “absent” with “0” in the attendance sheet.

Home example: Replace “Mum” with “Mother” in a family tree.

Nigerian example: Replace “Abj” with “Abuja” in an address column.

Illustration (ASCII):

   Before:  [Lagos] [LAG] [lagos] [Lagos State]
   After:   [Lagos] [Lagos] [Lagos] [Lagos]   (all fixed)

Mini summary: Replacing fixes errors and makes data consistent.

Lesson 12: Adding Custom Columns (Doing calculations)

Definition: A custom column is a new column that you create by doing a calculation – like Price × Quantity = Total.

Why important: It helps you get new information from existing data.

Simple explanation: Like adding a new row in your Lego building plan to count how many bricks you used.

Real-life example: Add a “Profit” column by subtracting Cost from Sales.

School example: Add a “Total Score” column that adds Test + Homework.

Home example: Add a “Total Cost” column = Price × Quantity.

Nigerian example: Add “Price in Naira” by converting Dollars to Naira using an exchange rate.

Illustration (ASCII):

   [Price] [Qty]  ➡️  [Total] = Price * Qty
   100      2      ➡️  200
   50       3      ➡️  150

Mini summary: Custom columns let you calculate new values from existing ones.

Lesson 13: Removing Duplicates (Keeping only one copy)

Definition: Duplicates are rows that are exactly the same. Removing them keeps only one copy.

Why important: Duplicates can make your counts wrong – like counting the same student twice.

Simple explanation: Like removing extra copies of the same picture from your photo album.

Real-life example: A voter list has the same name twice. Remove duplicates to get a unique list.

School example: A list of book titles has duplicate entries. Remove them to see unique titles.

Home example: A guest list has “Uncle Tunde” twice. Remove one.

Nigerian example: A company’s client list has the same phone number for two rows. Remove the duplicate.

Illustration (ASCII):

   Before:  [Ade] [Ade] [Bola] [Ade] [Chidi]
   After:   [Ade] [Bola] [Chidi]           (unique)

Mini summary: Remove duplicates to keep only one unique row of each value.

Lesson 14: Splitting Columns (One column into two)

Definition: Splitting means taking one column and dividing it into two – like splitting “Full Name” into “First Name” and “Last Name”.

Why important: Sometimes information is packed together; splitting makes it easier to work with.

Simple explanation: Like cutting a sandwich into two halves so you can share.

Real-life example: Split “Address” into “Street” and “City”.

School example: Split “Subject/Score” into “Subject” and “Score”.

Home example: Split “Item Colour” into “Item” and “Colour”.

Nigerian example: Split “Phone Number” into “Area Code” and “Number”.

Illustration (ASCII):

   Before:  [Full Name]
            Adeola Ojo
            Bola Smith
   After:   [First]  [Last]
            Adeola   Ojo
            Bola     Smith

Mini summary: Splitting separates combined data into two or more columns.

Lesson 15: Merging Columns (Two columns into one)

Definition: Merging is the opposite of splitting – we combine two columns into one, like “First Name” + “Last Name” = “Full Name”.

Why important: It helps to create a single identifier or a more readable column.

Simple explanation: Like putting two pieces of a puzzle together to make one big piece.

Real-life example: Merge “City” and “State” into “Location”.

School example: Merge “Class” and “Section” into “Class-Section”.

Home example: Merge “Day” and “Month” into “Date”.

Nigerian example: Merge “LGA” and “State” into “Full Address”.

Illustration (ASCII):

   Before:  [First]  [Last]
            Adeola   Ojo
   After:   [Full Name]
            Adeola Ojo

Mini summary: Merging combines two columns into one.

🔑 Key Vocabulary (simple definitions)

  • Data: Information like numbers, words, or pictures.
  • Power Query: A tool in Excel that cleans and organizes data.
  • Column: A vertical list in a table (goes up and down).
  • Row: A horizontal line of data in a table (goes left to right).
  • Filter: To show only rows that meet a rule.
  • Sort: To arrange rows in order (A→Z or 1→10).
  • Data type: Tells what kind of data is in a column (text, number, date).
  • Duplicate: A row that is exactly the same as another.
  • Transform: To change the shape or format of data.
  • Source: The place where data comes from (file, web, database).

🧠 Important Concepts

  • Power Query works with a step-by-step approach. Each action you do becomes a step.
  • You can undo or reorder steps – like building with Lego bricks.
  • Power Query does not change your original data – it makes a copy and cleans that.
  • You can refresh your query to get new data without redoing all the steps.

👣 Step-by-Step: First Power Query Project

  1. Open Excel and go to the Data tab.
  2. Click Get Data → From File → From Excel Workbook.
  3. Select your file and click Import.
  4. The Power Query Editor opens. You see your data.
  5. Remove any columns you don’t need.
  6. Filter rows to keep only what you want.
  7. Change data types (e.g., text to number).
  8. Sort the data by a column.
  9. Click Close & Load to put the clean data back into Excel.

🌍 Real-life Examples

  • A hospital cleans patient records to remove duplicate entries.
  • A supermarket combines sales from different stores into one report.
  • A teacher creates a class list and sorts by student name.

🇳🇬 Nigerian Examples

  • A Lagos-based e-commerce site uses Power Query to merge orders from Jumia, Konga, and their own website.
  • An Abuja school uses Power Query to combine attendance sheets from all classes.
  • A farmer in Ibadan uses Power Query to track his monthly harvest and sort by crop type.

🧸 Fun Examples for Kids

  • Sort your toy collection by size.
  • Filter your game scores to show only those above 100 points.
  • Remove duplicate Pokémon cards from your list.

🏠 Everyday Examples

  • Cleaning your phone contacts by removing duplicate numbers.
  • Sorting your music playlist by artist name.
  • Filtering your online shopping cart to show only items under ₦5000.

🧑‍🏫 Teacher Notes

  • Encourage students to think of data as “information treasures”.
  • Use physical objects (e.g., beads, cards) to demonstrate sorting and filtering.
  • Reinforce that Power Query is a tool – it does not make decisions, it just prepares data.

👪 Parent Tips

  • Help your child practice with a simple grocery list.
  • Ask questions like: “Why is it important to have neat data?”
  • Celebrate small wins – every cleaned table is a victory!

💡 Interesting Facts

  • Power Query was first introduced in Excel 2010 as an add‑in.
  • It can connect to over 40 different data sources!
  • The “M” language behind Power Query is named after the word “mashup”.

❓ Did You Know?

  • Power Query can combine data from multiple files in a folder automatically.
  • You can use Power Query without writing any code – just click!

🧾 Remember This

  • Always check your data types before doing calculations.
  • Keep your original data safe – Power Query never changes it.
  • Each step in Power Query is saved, so you can go back if you make a mistake.

⚠️ Common Mistakes

  • Forgetting to set the correct data type – then numbers don’t add up.
  • Removing the wrong column – double-check before you delete.
  • Not refreshing the query – your data might be old.

✅ Best Practices

  • Give your columns clear, short names.
  • Use filters to reduce data size early.
  • Document your steps (add comments) so others understand.

📊 Comparison Table: Clean vs Messy Data

FeatureMessy DataClean Data
SpellingInconsistent (LAG, lagos, Lagos)Uniform (Lagos)
Missing valuesSome cells emptyFilled with 0 or N/A
DuplicatesMany duplicate rowsUnique rows
SortingRandom orderLogical order (A→Z or 1→10)

📈 Flowchart: Power Query Workflow

   [ Start ]
       │
       ▼
   [ Get Data ]  ← from Excel, CSV, Web, etc.
       │
       ▼
   [ Transform ] ← filter, sort, rename, etc.
       │
       ▼
   [ Load ]      ← send clean data back to Excel
       │
       ▼
   [ Refresh ]   ← update with new data later

📝 End-of-Module Summary

Well done, young data expert! You have learned the first big steps in Power Query. You know what data is, how to connect to it, and how to clean it using columns, rows, filters, sorts, and data types. You also learned how to remove duplicates, split and merge columns, and even create new columns with calculations. Power Query is like a helpful robot that does the boring work so you can focus on the fun part – finding answers!

❓ Frequently Asked Questions (FAQ)

  1. What is Power Query? – A tool that cleans and organises data in Excel.
  2. Do I need to write code? – No, you can click buttons to do everything.
  3. Can I undo a step? – Yes, just delete the step from the list.
  4. Will Power Query change my original file? – No, it works on a copy.
  5. How do I get data from a CSV file? – Use Get Data → From Text/CSV.
  6. What is a data type? – It tells Power Query if a column is text, number, or date.
  7. Can I sort by more than one column? – Yes, sort by first column, then by second.
  8. What does “Refresh” do? – It runs the query again with new data.
  9. Is Power Query free? – Yes, it comes with Excel and Power BI.
  10. Can I use Power Query on a Mac? – Yes, in Excel for Mac, but some features differ.

📋 Review Questions

  1. What is data?
  2. Name two things you can do with Power Query.
  3. What is a column?
  4. What is a row?
  5. What does “filter” mean?
  6. Why do we sort data?
  7. Give an example of a data type.
  8. How do you remove duplicates?
  9. What is the difference between splitting and merging columns?
  10. How do you add a custom column?
  11. What is the Power Query Editor?
  12. Why is it important to set the correct data type?
  13. What does “Refresh” do in Power Query?
  14. Can Power Query connect to a web page?
  15. Why do we rename columns?

✏️ Fill-in-the-Blank

  1. Power Query is a tool in ______.
  2. A ______ is a vertical list in a table.
  3. To show only rows with scores above 50, you use a ______.
  4. ______ means arranging rows from A to Z.
  5. ______ tells Power Query if a column is text or number.
  6. To change “N/A” to “0” we use ______.
  7. ______ columns are new columns that we create with formulas.
  8. Removing ______ keeps only one copy of each row.
  9. Splitting a column divides it into ______ or more columns.
  10. Merging combines two columns into ______.

✅ True or False

  1. Power Query changes the original data file. (False)
  2. You cannot sort data in Power Query. (False)
  3. Data types help Power Query understand your data. (True)
  4. Filtering removes rows permanently. (False – it hides them)
  5. You can connect Power Query to a CSV file. (True)

🔘 Multiple Choice (select one)

  1. Power Query is found in which tab in Excel?
    A) Home B) Data C) Insert D) View Answer: B
  2. Which of these is a data type?
    A) Filter B) Sort C) Text D) Column Answer: C
  3. What does a filter do?
    A) Deletes rows B) Shows only rows that match a rule C) Adds new rows D) Changes column names Answer: B
  4. What is the opposite of splitting?
    A) Merging B) Filtering C) Sorting D) Removing Answer: A
  5. How do you remove duplicates?
    A) Sort B) Filter C) Remove Duplicates button D) Change data type Answer: C
  6. What does “Refresh” do?
    A) Saves the file B) Updates data from the source C) Deletes all steps D) Closes Power Query Answer: B
  7. Which is an example of a custom column?
    A) First Name B) Total = Price * Qty C) Last Name D) City Answer: B
  8. What does a sort do?
    A) Deletes rows B) Arranges rows in order C) Splits columns D) Merges columns Answer: B
  9. Where does Power Query get data from?
    A) Only Excel B) Many sources like Excel, CSV, Web C) Only databases D) Only text files Answer: B
  10. Which button do you click to finish and load data?
    A) Get Data B) Close & Load C) Refresh D) Sort Answer: B
  11. What is a column?
    A) Horizontal line B) Vertical line C) A filter D) A sort Answer: B
  12. Why do we rename columns?
    A) To make them shorter B) To make them clear and meaningful C) To delete them D) To sort them Answer: B
  13. Can you undo a step in Power Query?
    A) Yes B) No Answer: A
  14. What is a data source?
    A) A type of filter B) Where data comes from C) A kind of sort D) A column name Answer: B
  15. Which of these is NOT a transformation?
    A) Filter B) Sort C) Save file D) Add column Answer: C

🔗 Matching

Column AColumn B
1. FilterA. Arrange rows in order
2. SortB. Show only rows that match a rule
3. Data typeC. Tells if column is text or number
4. MergeD. Combine two columns into one
5. Remove duplicatesE. Keep only one copy of each row

Answers: 1-B, 2-A, 3-C, 4-D, 5-E

✍️ Short Answer

  1. Explain what Power Query does in one sentence.
  2. Why is it important to clean data before analysing it?
  3. Describe two ways to change the look of your data in Power Query.

📖 Scenario-based Exercises

Scenario: Your school has a list of 200 students with their test scores. Some names are spelled differently, some scores are missing, and the list is not in order. Describe how you would use Power Query to fix this.

Scenario 2: You are helping your uncle who runs a grocery store. He has a spreadsheet with sales from three different shops. Each shop has its own format. How can Power Query help?

👥 Group Activity

In groups of four, look at a sample dataset (provided by your teacher) with at least 20 rows and 5 columns. Together, use Power Query to:

  • Remove two unnecessary columns.
  • Filter rows to keep only those with a value greater than 50.
  • Sort the data by one column.
  • Rename at least two columns.

🧑 Individual Activity

Open a CSV file with your favourite game scores. Clean the data by removing duplicates, correcting the data type of the score column, and sorting by score. Write down the steps you took.

🗣️ Classroom Discussion Questions

  • Why do you think data cleaning is important in real life?
  • What other tools have you used that are similar to Power Query?
  • How would you explain Power Query to a friend who has never used Excel?

🛠️ Mini Project

Project: Create a Power Query report for a small business that sells three products (e.g., pens, books, erasers). The raw data has the date, product name, quantity sold, and price. Clean the data, add a total sales column, and sort by date. Load the clean data into a new sheet.

📥 Practical Assignment

Download a sample dataset from your teacher (or use any CSV file). Perform the following transformations: remove columns, filter rows, sort, change data types, remove duplicates, and add one custom column. Submit a screenshot of the Power Query Editor showing the steps.

🏆 Challenge Exercise

Find a messy dataset online (e.g., weather data, sports stats). Use Power Query to clean it completely. Write a short report explaining each step you took. Present your findings to the class.

🔍 Quiz Answers

Fill-in-the-Blank answers: 1. Excel, 2. column, 3. filter, 4. Sort, 5. Data type, 6. replace, 7. Custom, 8. duplicates, 9. two, 10. one.

True/False: 1-F, 2-F, 3-T, 4-F, 5-T.

Multiple Choice: 1B, 2C, 3B, 4A, 5C, 6B, 7B, 8B, 9B, 10B, 11B, 12B, 13A, 14B, 15C.

🎯 Key Takeaways

  • Power Query is your data cleaning superpower.
  • Always start by getting data, then transform it, and finally load it.
  • Cleaning data involves filtering, sorting, changing types, renaming, removing duplicates, and more.
  • Practice makes perfect – try different datasets!

🚀 Preparation for Module Two

In the next module, we will dive deeper into advanced transformations – like merging tables, grouping data, and writing our own formulas. You will also learn how to combine data from multiple files automatically. Keep practising the basics, and you’ll be ready for more exciting adventures with Power Query!


🌟 You have completed Module One – congratulations! On to Module Two! 🌟

2

Module One

Content for this lesson is coming soon.
3

Module Two

Module 2 · Power Query – Cleaning Like a Pro

🧹 Module 2: Power Query – Cleaning Like a Pro

Hello again, data explorer! 👋 In Module 1, we learned what Power Query is and how to do basic cleaning. Now, we will go deeper. We will learn how to fix common problems like extra spaces, wrong dates, and mixed text. We will also learn how to split columns and combine data from different sources. By the end of this module, you will be able to clean data like a professional! Let's dive in! 🏊‍♂️


🎯 Learning Objectives

  • ✅ Trim extra spaces from text.
  • ✅ Fix date formats.
  • ✅ Split columns into multiple columns.
  • ✅ Combine columns into one.
  • ✅ Replace values (e.g., change "N/A" to "0").
  • ✅ Use conditional columns to create new data.
  • ✅ Group data to see totals.
  • ✅ Pivot and unpivot tables.
  • ✅ Merge queries from different sources.

📖 Warm-up Story: The Bakery Mix-up

In a small bakery in Ibadan, Nigeria, the baker, Mr. Ade, had a problem. He kept records of his daily bread sales, but his data was messy. Some dates were written as "12/05/2025" and others as "May 12, 2025". Some customer names had extra spaces like " Chidi ". He also had a column called "Full Name" but he needed separate "First Name" and "Last Name". He spent hours fixing these problems by hand. Then his daughter, Ngozi, who had just learned Power Query, said, "Daddy, let me help!" She used Power Query to trim spaces, fix dates, split names, and even combine data from two different files. In just a few minutes, everything was perfect. Mr. Ade was amazed and gave Ngozi an extra piece of cake! 🎂

This module will teach you all the tricks Ngozi used!


📚 Main Lessons

Lesson 1: Trim – Removing Extra Spaces

Definition: Trim means removing unwanted spaces from the beginning or end of text.

Why important: Extra spaces can make it hard to search or match data. "Chidi" and "Chidi " are not the same to a computer.

Simple explanation: It's like cleaning the edges of a paper before putting it in a frame.

Real-life example: A customer list has " Ada " – trim makes it "Ada".

School example: A teacher trims student names before printing certificates.

Home example: Your mom trims the grocery list to remove extra spaces.

Nigerian example: A bank trims account holder names to avoid mismatches.

Illustration:

   Before: "  Bola  "  →  After: "Bola"

Mini summary: Trim removes extra spaces from text.


Lesson 2: Clean – Removing Non-Printable Characters

Definition: Clean removes characters that are not visible, like line breaks or special symbols.

Why important: These characters can cause errors in calculations or sorting.

Simple explanation: Like wiping dust off a table before placing a book.

Real-life example: Data copied from a website may have hidden symbols – Clean removes them.

School example: A project list from a website has weird characters – Clean fixes it.

Home example: A contact list copied from an email has extra symbols.

Nigerian example: A farmer's crop data from a PDF has hidden line breaks.

Illustration:

   Before: "Mango🍎" (with hidden symbol)  →  After: "Mango"

Mini summary: Clean removes invisible characters.


Lesson 3: Fixing Date Formats

Definition: Dates can be written in many ways. Power Query can change them to a standard format.

Why important: If dates are in different formats, you cannot sort or calculate correctly.

Simple explanation: It's like making sure all your friends write their birthdays the same way: DD/MM/YYYY.

Real-life example: Change "2025-12-31" to "31-Dec-2025".

School example: Make all exam dates look the same in the school calendar.

Home example: Fix the dates on your family's holiday photos.

Nigerian example: A school in Enugu standardises admission dates.

Illustration:

   Before: 12/31/2025  →  After: 31/12/2025 (consistent)

Mini summary: Standardise date formats for consistency.


Lesson 4: Splitting Columns

Definition: Splitting means taking one column and dividing it into two or more columns.

Why important: Sometimes one column has too much information, like "Chidi Okonkwo" – we want "Chidi" and "Okonkwo".

Simple explanation: Like cutting a sandwich into two halves.

Real-life example: Split "Full Name" into "First Name" and "Last Name".

School example: Split "Subject-Grade" into "Subject" and "Grade".

Home example: Split "Address" into "City" and "Street".

Nigerian example: Split "Lagos-Nigeria" into "City" and "Country".

Illustration:

   Before: "Chidi Okonkwo"  →  After: "Chidi" | "Okonkwo"

Mini summary: Split columns to separate information.


Lesson 5: Combining Columns

Definition: Combining merges two or more columns into one.

Why important: Sometimes you need a full name or full address from separate parts.

Simple explanation: Like joining two puzzle pieces to make a bigger piece.

Real-life example: Merge "First Name" and "Last Name" into "Full Name".

School example: Merge "Class" and "Section" into "Class-Section".

Home example: Merge "Street" and "Number" into "Address".

Nigerian example: Merge "LGA" and "State" into "Location".

Illustration:

   Before: "Chidi" | "Okonkwo"  →  After: "Chidi Okonkwo"

Mini summary: Combine columns to create new information.


Lesson 6: Replace Values

Definition: Replace Values changes specific text or numbers to something else.

Why important: You might have abbreviations or errors that need to be corrected.

Simple explanation: Like using a white-out pen to fix a mistake.

Real-life example: Change "N/A" to "0".

School example: Change "Absent" to "A".

Home example: Change "Kg" to "Kilogram".

Nigerian example: Change "LAG" to "Lagos".

Illustration:

   Before: "N/A"  →  After: "0"

Mini summary: Replace values to fix errors or standardise.


Lesson 7: Conditional Columns

Definition: A conditional column creates a new column based on a condition (if-then logic).

Why important: You can categorise data automatically.

Simple explanation: Like saying, "If it rains, take an umbrella; else, take a hat."

Real-life example: If sales > 1000, mark "High"; else "Low".

School example: If score ≥ 70, mark "Pass"; else "Fail".

Home example: If price > 500, mark "Expensive"; else "Cheap".

Nigerian example: If crop yield > 500kg, mark "Good Harvest".

Illustration:

   Sales  |  Category
   1500   |  High
   700    |  Low

Mini summary: Conditional columns add categories based on rules.


Lesson 8: Group By

Definition: Group By combines rows with the same value in a column and calculates something like sum, average, or count.

Why important: It summarises large data so you can see totals.

Simple explanation: Like grouping your toys by colour and counting how many of each colour.

Real-life example: Group sales by product to see total sales per product.

School example: Group students by class and count how many in each class.

Home example: Group expenses by category (food, rent) and sum them.

Nigerian example: Group farm produce by crop and sum the weight.

Illustration:

   Product  |  Sales
   Mango    |  100
   Mango    |  150
   Orange   |  200
   Group By Product → Mango:250, Orange:200

Mini summary: Group By summarises data by categories.


Lesson 9: Pivot Columns

Definition: Pivot turns a column's values into multiple columns.

Why important: It makes data wider and easier to compare.

Simple explanation: Like turning a list of months into separate columns for January, February, etc.

Real-life example: Pivot months to see each month as a column.

School example: Pivot subjects to see each subject as a column with grades.

Home example: Pivot types of chores to see time spent per type.

Nigerian example: Pivot regions to see sales per region.

Illustration:

   Before: Month | Sales
           Jan   | 100
           Feb   | 200
   After:  Jan | Feb
           100 | 200

Mini summary: Pivot makes data wider.


Lesson 10: Unpivot Columns

Definition: Unpivot is the opposite of pivot – it turns multiple columns into rows.

Why important: Sometimes you need data tall (long) instead of wide.

Simple explanation: Like taking a table with Jan, Feb, Mar and turning it into a list of Month-Sales.

Real-life example: Unpivot monthly sales columns into a single column of months.

School example: Unpivot subject columns into a list of subjects.

Home example: Unpivot expense columns into a list of expenses.

Nigerian example: Unpivot crop yields by month.

Illustration:

   Before: Jan | Feb | Mar
           100 | 200 | 150
   After: Month | Sales
          Jan   | 100
          Feb   | 200
          Mar   | 150

Mini summary: Unpivot makes data taller (more rows).


Lesson 11: Merging Queries (from different sources)

Definition: Merging joins two queries (tables) from different sources using a common column.

Why important: You often have data in separate files – merging brings them together.

Simple explanation: Like sticking two photos together to make a bigger picture.

Real-life example: Merge customer data from Excel with order data from a database.

School example: Merge student list from one file with test scores from another.

Home example: Merge your toy list with a price list from a website.

Nigerian example: Merge school attendance from Excel with exam results from CSV.

Illustration:

   Query1: StudentID, Name
   Query2: StudentID, Score
   Merge → StudentID, Name, Score

Mini summary: Merging combines queries from different sources.


Lesson 12: Appending Queries

Definition: Appending stacks two queries (tables) on top of each other.

Why important: If you have monthly sales in separate files, you can combine them into one.

Simple explanation: Like stacking building blocks.

Real-life example: Append January sales query with February sales query.

School example: Append test scores from Class A and Class B.

Home example: Append your allowance records from two years.

Nigerian example: Append daily sales from all branches.

Illustration:

   Query Jan: Ada, 100
   Query Feb: Bola, 200
   Append → Ada, 100; Bola, 200

Mini summary: Append stacks queries vertically.


Lesson 13: Adding Custom Columns

Definition: A custom column is a new column that you create using a formula.

Why important: You can calculate new data, like total price = quantity * price.

Simple explanation: Like using a calculator to add numbers and writing the answer in a new column.

Real-life example: Create "Total Sales" = Quantity * Unit Price.

School example: Create "Total Score" = Test1 + Test2.

Home example: Create "Total Cost" = Items * Price.

Nigerian example: Create "Total Harvest" = Bags * Weight.

Illustration:

   Quantity | Price | Total (custom)
   2        | 500   | 1000

Mini summary: Custom columns let you create new data with formulas.


Lesson 14: Using the M Language (Introduction)

Definition: M is the language behind Power Query. It writes the steps for you.

Why important: You can see the code and learn to write your own advanced steps.

Simple explanation: It's like the recipe behind your favourite dish. Power Query writes it for you.

Real-life example: When you click a button, Power Query writes M code in the background.

School example: Like the teacher writing notes on the board – M is the notes.

Home example: The instructions for a toy are like M code.

Nigerian example: A recipe for jollof rice is like M code – step-by-step.

Illustration:

   let
       Source = Excel.Workbook(...),
       Table1 = Source{[Item="Sheet1"]}[Data]
   in
       Table1

Mini summary: M is the code behind your cleaning steps.


Lesson 15: Refreshing Data

Definition: Refreshing updates your query to get the latest data.

Why important: If new data comes in, you can refresh to see it without redoing all steps.

Simple explanation: Like turning on the tap to get fresh water.

Real-life example: You refresh your sales query to include today's sales.

School example: Refresh attendance to see who is present today.

Home example: Refresh your chore list to see new tasks.

Nigerian example: Refresh crop data after a new harvest.

Illustration:

   Click Refresh → New data appears

Mini summary: Refresh brings in new data.


📖 Key Vocabulary (with simple definitions)

  • Trim: Remove extra spaces.
  • Clean: Remove invisible characters.
  • Split: Divide one column into many.
  • Combine: Merge columns into one.
  • Replace Values: Change specific text or numbers.
  • Conditional Column: New column based on an if-then rule.
  • Group By: Summarise data by categories.
  • Pivot: Turn rows into columns.
  • Unpivot: Turn columns into rows.
  • Merge: Join two queries side by side.
  • Append: Stack queries top to bottom.
  • Custom Column: Column created with a formula.
  • M Language: The code language of Power Query.
  • Refresh: Update data.

🧠 Important Concepts

  • Data transformation is the process of changing data to make it useful.
  • Consistency is key – all data should be in the same format.
  • Reusability – once you create a query, you can reuse it with new data by refreshing.
  • Automation – Power Query automates repetitive cleaning tasks.
  • Data types still matter – always check them after transformations.

📝 Step-by-Step Explanations

Trim and Clean:

  1. Select the column.
  2. Go to Transform → Format → Trim (or Clean).

Split Column:

  1. Select the column.
  2. Go to Transform → Split Column → By Delimiter (e.g., space).
  3. Choose "At each occurrence" or "At the left-most delimiter".

Combine Columns:

  1. Select columns.
  2. Go to Add Column → Merge Columns.
  3. Choose a separator (e.g., space).

Replace Values:

  1. Select column.
  2. Go to Transform → Replace Values.
  3. Enter value to find and value to replace with.

Conditional Column:

  1. Go to Add Column → Conditional Column.
  2. Set column name, condition (if), and output.

Group By:

  1. Go to Transform → Group By.
  2. Choose column to group by.
  3. Choose aggregation (Sum, Average, Count).

Pivot:

  1. Select column to pivot.
  2. Go to Transform → Pivot Column.
  3. Choose values column and aggregation.

Unpivot:

  1. Select columns to unpivot.
  2. Go to Transform → Unpivot Columns.

Merge Queries:

  1. Go to Home → Merge Queries.
  2. Select the second query and matching columns.
  3. Choose join kind (usually Left Outer).

Append Queries:

  1. Go to Home → Append Queries.
  2. Select the second query.

Custom Column:

  1. Go to Add Column → Custom Column.
  2. Write formula (e.g., [Quantity] * [Price]).

🌍 Real-life Examples

  • Retail: Clean product names by trimming spaces and replacing abbreviations.
  • Healthcare: Split patient names, clean addresses, and group by disease.
  • Finance: Replace "NULL" with 0, pivot months for cash flow.
  • Education: Group students by class, pivot subjects to see grade distribution.

🇳🇬 Nigerian Examples

  • Bank: Trim account holder names, replace "N/A" with "0" in transaction data.
  • Agriculture: Group crop data by state, pivot to see monthly yields.
  • School: Split student names, combine class and stream, conditional column for pass/fail.
  • Market: Clean item names, replace misspellings, unpivot weekly sales.

🧸 Fun Examples Children Can Relate To

  • Toys: Trim toy names, split "LEGO Star Wars" into "LEGO" and "Star Wars".
  • Games: Group video game scores by player, pivot to see scores per level.
  • Books: Combine author first and last name, conditional column for "Fiction" or "Non-fiction".
  • Snacks: Replace "choc" with "chocolate", group by flavour.

🏠 Everyday Examples

  • Grocery: Trim item names, replace "ltr" with "litre".
  • Chores: Split "Clean Room" into "Clean" and "Room".
  • Allowance: Group by week, sum amounts.
  • Phone contacts: Combine first and last name, trim extra spaces.

👩‍🏫 Teacher Notes

  • Use the bakery story to motivate students.
  • Demonstrate each step live in Excel.
  • Provide a messy dataset for students to practice all transformations.
  • Encourage students to create their own conditional columns.
  • Emphasise that practice is key – the more they do, the better they get.

👪 Parent Tips

  • Help your child find a messy dataset online (like weather data).
  • Let them practice trimming and splitting at home.
  • Show them how to refresh data when new information comes.
  • Praise their efforts and encourage experimentation.

💡 Interesting Facts

  • Power Query can handle over 1 million rows of data.
  • It can connect to databases like SQL Server and Oracle.
  • Power Query is used by data analysts in almost every industry.
  • The "M" language is named after the "Mashup" concept.
  • You can use Power Query to combine data from Facebook and Twitter.

🤔 Did You Know?

  • Did you know that you can use Power Query to clean data from your email attachments?
  • Did you know that Power Query can automatically detect data types for you?
  • Did you know that you can share your Power Query steps with friends by sending them the Excel file?

🔔 Remember This

  • 🧼 Trim and Clean to remove unwanted characters.
  • ✂️ Split columns to separate information.
  • ➕ Combine columns to create full names or addresses.
  • 🔄 Replace values to fix errors.
  • ❓ Conditional columns add categories.
  • 📊 Group By summarises data.
  • 🔄 Pivot and Unpivot change the shape of your table.
  • 🔗 Merge and Append combine data from different sources.

⚠️ Common Mistakes

  • Mistake 1: Not trimming spaces – leads to mismatches.
  • Mistake 2: Splitting by the wrong delimiter (e.g., using comma instead of space).
  • Mistake 3: Forgetting to change data types after splitting.
  • Mistake 4: Grouping by wrong column – getting wrong totals.
  • Mistake 5: Pivoting without selecting the correct value column.
  • Mistake 6: Merging on columns with different data types.

✅ Best Practices

  • Always trim and clean text columns first.
  • Standardise date formats early.
  • Use conditional columns to add meaningful categories.
  • Group and pivot only when needed.
  • Name your queries clearly (e.g., "SalesData_Cleaned").
  • Refresh to test if your query works with new data.

📊 Illustrations

Flowchart: Cleaning Process

   [ Load Data ]
        |
        V
   [ Trim & Clean ]
        |
        V
   [ Split/Combine ]
        |
        V
   [ Replace Values ]
        |
        V
   [ Conditional Column ]
        |
        V
   [ Group / Pivot ]
        |
        V
   [ Merge / Append ]
        |
        V
   [ Load to Excel ]

Timeline: Advanced Steps

   1. Trim   →  2. Clean  →  3. Split  →  4. Combine
        ↓          ↓            ↓            ↓
   5. Replace  →  6. Conditional  →  7. Group By
        ↓              ↓                ↓
   8. Pivot   →  9. Unpivot  →  10. Merge/Append

Comparison: Pivot vs Unpivot

FeaturePivotUnpivot
EffectMakes data widerMakes data taller
ColumnsIncreasesDecreases
RowsDecreasesIncreases
Use caseComparative analysisNormalisation

📌 End-of-Module Summary

Congratulations! 🎉 You have completed Module 2. You now know how to:

  • Trim and clean text.
  • Split and combine columns.
  • Replace values and create conditional columns.
  • Group, pivot, and unpivot data.
  • Merge and append queries.
  • Add custom columns and refresh data.

You are now a Power Query cleaning expert! Keep practising with different datasets.


❓ Frequently Asked Questions (10)

  1. What is the difference between Trim and Clean? Trim removes spaces, Clean removes invisible characters.
  2. Can I split a column by multiple delimiters? Yes, you can split by delimiter and choose options.
  3. What is the use of conditional columns? To create categories based on conditions.
  4. How do I undo a pivot? Use Unpivot to reverse it.
  5. Can I merge more than two queries? Yes, you can merge multiple queries step by step.
  6. What is the difference between Merge and Append? Merge adds columns, Append adds rows.
  7. Can I use custom formulas in custom columns? Yes, you can write formulas like [Qty]*[Price].
  8. What does Refresh do? Updates the data with the latest from the source.
  9. Is the M language difficult to learn? No, Power Query writes it for you – you can learn gradually.
  10. Can I reuse a query with new data? Yes, just refresh or change the source.

📝 Review Questions (15)

  1. What does Trim do?
  2. What does Clean do?
  3. Why would you split a column?
  4. How do you combine two columns?
  5. What is Replace Values used for?
  6. What is a conditional column?
  7. What does Group By do?
  8. What is the difference between Pivot and Unpivot?
  9. How do you merge two queries?
  10. How do you append queries?
  11. What is a custom column?
  12. What is the M language?
  13. What does Refresh do?
  14. Give an example of a conditional column rule.
  15. Why is cleaning data important?

✏️ Fill-in-the-Blank

  1. Trim removes _______________ spaces. (extra)
  2. Clean removes _______________ characters. (invisible)
  3. Splitting divides one column into _______________. (many)
  4. Combine merges columns into _______________. (one)
  5. Replace Values changes specific _______________ or numbers. (text)
  6. A conditional column uses an _______________ condition. (if-then)
  7. Group By summarises data by _______________. (categories)
  8. Pivot makes data _______________. (wider)
  9. Unpivot makes data _______________. (taller)
  10. Merge adds _______________ from another query. (columns)
  11. Append adds _______________ from another query. (rows)
  12. A custom column is created with a _______________. (formula)
  13. M is the _______________ behind Power Query. (language)
  14. Refresh _______________ the data. (updates)

✅ True or False

  1. Trim removes spaces from the middle of text. (False – only beginning and end)
  2. Clean removes invisible characters. (True)
  3. Splitting a column always creates two columns. (False – can create many)
  4. Combine columns can use a separator. (True)
  5. Replace Values can only change numbers. (False – text too)
  6. Conditional columns are based on if-then logic. (True)
  7. Group By only works with numbers. (False – can count text too)
  8. Pivot makes data taller. (False – wider)
  9. Unpivot makes data wider. (False – taller)
  10. Merge combines queries side by side. (True)
  11. Append combines queries top to bottom. (True)
  12. Custom columns always use the M language. (True)
  13. Refresh deletes your data. (False – it updates)

🔘 Multiple Choice Questions

  1. Which function removes extra spaces?
    A) Clean B) Trim C) Split D) Combine
    Answer: B
  2. Which function removes invisible characters?
    A) Trim B) Clean C) Split D) Merge
    Answer: B
  3. To separate "First Last" into two columns, use:
    A) Combine B) Split C) Replace D) Group By
    Answer: B
  4. To merge "First" and "Last" into "Full", use:
    A) Split B) Combine C) Replace D) Pivot
    Answer: B
  5. Which step changes "N/A" to "0"?
    A) Replace Values B) Trim C) Clean D) Split
    Answer: A
  6. A conditional column uses:
    A) If-then B) Sum C) Average D) Count
    Answer: A
  7. Which step summarises data by categories?
    A) Pivot B) Unpivot C) Group By D) Merge
    Answer: C
  8. Pivot makes data:
    A) Wider B) Taller C) Smaller D) Messier
    Answer: A
  9. Unpivot makes data:
    A) Wider B) Taller C) Smaller D) Messier
    Answer: B
  10. Merge adds:
    A) Rows B) Columns C) Cells D) Sheets
    Answer: B
  11. Append adds:
    A) Rows B) Columns C) Cells D) Sheets
    Answer: A
  12. A custom column is created with a:
    A) Formula B) Filter C) Sort D) Pivot
    Answer: A
  13. M language is used in:
    A) Power Query B) Excel formulas C) VBA D) Word
    Answer: A
  14. Refresh does:
    A) Deletes data B) Updates data C) Sorts data D) Filters data
    Answer: B
  15. Which is not a cleaning step?
    A) Trim B) Split C) Print D) Replace Values
    Answer: C

🔗 Matching Exercise

Column AColumn B
1. TrimA. Remove invisible characters
2. CleanB. Divide a column
3. SplitC. Remove extra spaces
4. CombineD. Merge columns
5. Replace ValuesE. Change specific text

Answers: 1-C, 2-A, 3-B, 4-D, 5-E


📝 Short Answer Questions

  1. Explain the difference between Trim and Clean.
  2. When would you use Split instead of Combine?
  3. Give an example of a conditional column.
  4. What is the advantage of using Group By?
  5. Why is it important to refresh data?

📖 Scenario-based Exercises

  1. Scenario: You have a list of customer names with extra spaces and some have titles like "Mr." and "Mrs." Write steps to clean and split titles.
  2. Scenario: You have monthly sales data in separate Excel files. Describe how to append them into one query.
  3. Scenario: You have a table with product names, quantities, and prices. Create a custom column for total sales.

👥 Group Activity

Activity: In groups, find a messy dataset online (e.g., weather data). Load it into Power Query and apply at least 10 cleaning and transformation steps. Present your final table.


🧑 Individual Activity

Activity: Create a dataset of 20 fictional students (Name, Subject, Score). Include extra spaces, inconsistent dates, and duplicate values. Clean and transform it using Power Query.


🗣️ Classroom Discussion Questions

  1. Why is data cleaning important in the real world?
  2. Can you think of a situation where pivot would be useful?
  3. How does Power Query save time for businesses?
  4. What would happen if you forgot to trim spaces?
  5. How can you share your Power Query knowledge with others?

🛠️ Mini Project

Project: Collect data from 10 of your classmates (Name, Age, Favourite Subject, Test Score). Clean it using Power Query: trim, split name, conditional column for pass/fail, group by subject to get average scores. Load the final report.


💻 Practical Assignment

Assignment: Download a CSV file of sales data from your teacher. Load it into Power Query. Apply the following:

  1. Trim product names
  2. Clean any invisible characters
  3. Split Product Name and Category
  4. Combine First and Last Name of salesperson
  5. Replace "NULL" with 0
  6. Create a conditional column for High/Low sales
  7. Group by product to get total sales
  8. Pivot by month
  9. Refresh to test
  10. Close & Load

Submit the cleaned file.


🏆 Challenge Exercise

Challenge: Use Power Query to get data from a web page (e.g., Wikipedia table). Clean the data: remove duplicates, split columns, and create a conditional column. Then merge it with another table you have. Show your final result.


🔑 Quiz Answers

All answers are provided within each exercise section above.


🎁 Key Takeaways

  • Advanced cleaning makes data perfect.
  • Splitting and combining help organise information.
  • Conditional columns add intelligence.
  • Grouping and pivoting summarise data.
  • Merging and appending combine sources.
  • Refresh keeps data current.

📚 Preparation for Module 3

In Module 3, we will learn about Advanced Data Analysis – we will use Power Query to perform complex calculations, create dynamic reports, and automate workflows. We will also learn how to optimise queries for speed. Keep practising all the steps from Modules 1 and 2. You are doing great!


🎉 End of Module 2 – Keep cleaning and exploring! 🎉

4

Module Three

Module 3 · Power Query – Combining & Shaping Data Like a Pro

📊 Module 3: Power Query – Combining & Shaping Data Like a Pro

Hello, amazing data explorer! 👋 You have already learned how to clean messy data in Modules 1 and 2. Now, we are going to become data shapers! Imagine you are a sculptor with a big block of clay. You can cut it, join pieces, and shape it into anything you want. Power Query lets you do the same with data. In this module, we will learn how to combine data from many different sources, shape it exactly the way we need, and even automate the whole process. By the end, you will be able to handle data like a true expert! Let's jump in! 🏊‍♂️


🎯 Learning Objectives

  • ✅ Combine data from multiple Excel files.
  • ✅ Combine data from different folders.
  • ✅ Use the "Combine Files" feature.
  • ✅ Create parameters to make your queries flexible.
  • ✅ Use functions to reuse steps.
  • ✅ Understand query dependencies.
  • ✅ Optimise query performance.
  • ✅ Create a dynamic data refresh.
  • ✅ Build a complete data transformation workflow.

📖 Warm-up Story: The School Project

In a big school in Abuja, Nigeria, the principal, Mrs. Okafor, needed to combine exam results from all 30 classes. Each class teacher had sent an Excel file with marks. Mrs. Okafor was worried because she had to open each file, copy the data, and paste them into one big sheet. That would take hours! Her son, Tunde, who was 11 years old and loved computers, said, "Mummy, let me try something." He used Power Query to combine all the files from a folder with just a few clicks. He also used a parameter so that if new files were added, the query would automatically include them. In just 5 minutes, Tunde had a complete master sheet with all the results. Mrs. Okafor was so proud! 🏆

This module will teach you the magic Tunde used!


📚 Main Lessons

Lesson 1: Combining Data from Multiple Excel Files

Definition: Combining data from multiple files means taking information from several workbooks and putting it into one table.

Why important: Often data is split across many files (e.g., sales per month). Combining saves you from copying and pasting.

Simple explanation: It's like collecting all your Lego sets and putting all the bricks into one big box.

Real-life example: A shop owner has a separate Excel file for each day's sales. Power Query can combine them into one file.

School example: Your teacher has exam scores in separate files for each class. You can combine them.

Home example: Your family has a budget file for each year. You can combine them.

Nigerian example: A farmer has crop yield data for each month in separate files. Combine them to see the whole year.

Illustration:

   File1: Jan Sales   File2: Feb Sales   File3: Mar Sales
        \                  |                  /
         \                 |                 /
          V                V                V
         +-----------------------------------+
         |    Combined Sales (All Months)    |
         +-----------------------------------+

Mini summary: Combining files brings scattered data together.


Lesson 2: Combining Data from a Folder

Definition: This is a special feature where Power Query combines all files of a certain type (e.g., Excel or CSV) inside a folder.

Why important: It's super efficient – you don't even need to open the files.

Simple explanation: Like telling your friend to bring all the books from a shelf, not just one book.

Real-life example: You have a folder with 365 daily sales files. Power Query can combine them all.

School example: A folder with all student attendance sheets for the term.

Home example: A folder with photos (but for data, it's files!).

Nigerian example: A bank has transaction files for each branch in one folder.

Illustration:

   📁 Folder
   ├── Jan.csv
   ├── Feb.csv
   ├── Mar.csv
   └── ...
   [Power Query] → One big table

Mini summary: Combining from a folder is like a bulk action.


Lesson 3: Using the "Combine Files" Feature

Definition: Power Query has a built-in button called "Combine Files" that does everything automatically.

Why important: It saves you from setting up steps manually – it's a shortcut.

Simple explanation: Like a one-click magic wand.

Real-life example: Click "Combine Files" and Power Query detects the structure.

School example: Combine all class files with one click.

Home example: Combine your allowance records.

Nigerian example: Combine branch sales files easily.

Illustration:

   Get Data → From Folder → Combine & Transform Data

Mini summary: "Combine Files" is a quick way to merge many files.


Lesson 4: Introduction to Parameters

Definition: A parameter is a value you can change easily, like a year or a product name, to make your query flexible.

Why important: Instead of editing the query every time, you change the parameter.

Simple explanation: Like a variable in a video game – you can change it to get different results.

Real-life example: Create a parameter for "Year" – change it from 2025 to 2026 and the query updates.

School example: Parameter for "Class" – change to see results for different classes.

Home example: Parameter for "Month" – change to see expenses for that month.

Nigerian example: Parameter for "Region" – change to see data for Lagos, Abuja, or Kano.

Illustration:

   Parameter: Year = 2025
   Query uses Year to filter data.
   Change to 2026 → Query updates automatically.

Mini summary: Parameters make queries dynamic and reusable.


Lesson 5: Creating Parameters in Power Query

Definition: You create a parameter by going to Home → Manage Parameters → New Parameter.

Why important: It's easy to do and very powerful.

Simple explanation: You name the parameter and give it a default value.

Real-life example: Parameter "MinSales" = 1000.

School example: Parameter "PassMark" = 70.

Home example: Parameter "Budget" = 5000.

Nigerian example: Parameter "State" = "Lagos".

Illustration:

   Manage Parameters → New
   Name: Year
   Type: Number
   Current Value: 2025

Mini summary: Creating parameters is simple and useful.


Lesson 6: Using Parameters in Your Queries

Definition: You can use parameters in filter, custom columns, or file paths.

Why important: This makes your query answer different questions without changing steps.

Simple explanation: Like using a variable in math – x + 2, where x is the parameter.

Real-life example: Filter sales where Year = [Year Parameter].

School example: Show only students with Score >= [PassMark].

Home example: Show expenses where Amount <= [Budget].

Nigerian example: Filter data for [State] = "Lagos".

Illustration:

   Filter Rows → Where [Year] = [YearParam]

Mini summary: Parameters let you control your query from one place.


Lesson 7: Introduction to Functions

Definition: A function is a reusable set of steps that you can apply to different data.

Why important: Instead of writing the same steps again and again, you use a function.

Simple explanation: Like a recipe that you can use for different ingredients.

Real-life example: A function that cleans any table you give it.

School example: A function to calculate total marks for any subject.

Home example: A function to convert currencies.

Nigerian example: A function to calculate VAT on any price.

Illustration:

   Function: CleanData (Input Table) → Returns Cleaned Table
   Apply to Table1, Table2, Table3.

Mini summary: Functions are reusable cleaning machines.


Lesson 8: Creating a Function

Definition: You create a function by writing M code, but Power Query can help you create it from a query.

Why important: You can automate repetitive tasks.

Simple explanation: You build a machine that does the same job on different inputs.

Real-life example: Create a function that removes duplicates from any table.

School example: Create a function that standardises names.

Home example: Create a function that categorises expenses.

Nigerian example: Create a function that formats phone numbers.

Illustration:

   Query1 (cleans data) → Convert to Function
   Name: CleanFunction
   Parameter: InputTable

Mini summary: Functions are custom tools you build.


Lesson 9: Using Functions in Queries

Definition: Once you have a function, you can invoke (call) it with different tables.

Why important: It saves time and ensures consistency.

Simple explanation: You call the function like you call a friend to help.

Real-life example: Invoke CleanFunction on SalesData.

School example: Invoke StandardiseName on student list.

Home example: Invoke CurrencyConverter on prices.

Nigerian example: Invoke PhoneFormatter on customer list.

Illustration:

   Invoke Custom Function → Select Function → Apply

Mini summary: Using functions is like delegating work.


Lesson 10: Query Dependencies

Definition: Dependencies show how queries are connected – which query uses which.

Why important: If you change one query, you know which others will be affected.

Simple explanation: Like a family tree – if grandma changes, everyone is affected.

Real-life example: Query A is used by Query B and C.

School example: ClassData is used by Report and Dashboard.

Home example: Expenses used by Summary and Chart.

Nigerian example: SalesData used by Profit and Revenue queries.

Illustration:

   [BaseData] → [CleanedData] → [FinalReport]
       |              |
       V              V
   [Backup]       [Summary]

Mini summary: Dependencies help you manage your queries.


Lesson 11: Optimising Query Performance

Definition: Optimising means making your query run faster and use less memory.

Why important: Large data can be slow – you want it to be quick.

Simple explanation: Like cleaning your room quickly by putting things in the right place.

Real-life example: Only load columns you need, not all columns.

School example: Only load the student names and scores, not their photos.

Home example: Only load the current year's expenses.

Nigerian example: Only load data for the current region.

Illustration:

   ✅ Good: Load only needed columns.
   ❌ Bad: Load all columns.

Mini summary: Optimisation makes queries faster.


Lesson 12: Dynamic Data Refresh

Definition: Dynamic refresh means your query updates automatically when the source data changes.

Why important: You always have the latest data without doing anything.

Simple explanation: Like a news ticker that updates automatically.

Real-life example: Sales data refreshes every morning.

School example: Attendance refreshes each period.

Home example: Budget refreshes when you add new expenses.

Nigerian example: Stock data refreshes every hour.

Illustration:

   Data Source → Power Query → Refresh (scheduled) → Updated Report

Mini summary: Dynamic refresh keeps data current.


Lesson 13: Building a Complete Workflow

Definition: A workflow is a series of steps from start to finish – load, clean, transform, combine, and output.

Why important: It gives you a structured way to handle data projects.

Simple explanation: Like a recipe – first gather ingredients, then chop, cook, and serve.

Real-life example: Load daily files → Clean → Combine → Generate report.

School example: Load class files → Standardise → Merge → Calculate averages.

Home example: Load receipts → Categorise → Summarise by month.

Nigerian example: Load branch data → Clean → Combine → Create dashboard.

Illustration:

   1. Get Data (from Folder)
          |
          V
   2. Combine Files
          |
          V
   3. Clean & Transform
          |
          V
   4. Group & Pivot
          |
          V
   5. Load to Excel

Mini summary: A workflow organises your entire data process.


Lesson 14: Error Handling

Definition: Error handling means managing problems when data is missing or in the wrong format.

Why important: Sometimes files are corrupt or have different structures – you can handle it gracefully.

Simple explanation: Like when you drop a glass, you clean it up instead of crying.

Real-life example: If a file is missing, Power Query can skip it and continue.

School example: If a student's data is missing, use a default value.

Home example: If a receipt is missing, estimate the amount.

Nigerian example: If a branch file is missing, use previous month's data.

Illustration:

   Try: Load File
   If error → Skip file

Mini summary: Error handling makes your queries robust.


Lesson 15: Documenting Your Queries

Definition: Documenting means adding notes or descriptions to your queries so others (or you) can understand them later.

Why important: After a few months, you might forget what a step does. Documentation helps.

Simple explanation: Like writing labels on storage boxes.

Real-life example: Add a comment in the M code: "This step removes duplicates".

School example: Write notes on your project steps.

Home example: Label your queries: "Jan Expenses", "Feb Expenses".

Nigerian example: Add comments to explain logic to colleagues.

Illustration:

   // This step splits Full Name into First and Last
   // This step filters out rows with missing values

Mini summary: Documentation helps you and others understand your work.


📖 Key Vocabulary (with simple definitions)

  • Combine: To bring together from different sources.
  • Folder: A place on your computer where files are stored.
  • Parameter: A value you can change to make your query flexible.
  • Function: A reusable set of steps.
  • Dependency: When one query uses another.
  • Optimise: To make faster and more efficient.
  • Dynamic Refresh: Automatic update of data.
  • Workflow: A series of steps from start to finish.
  • Error Handling: Managing problems gracefully.
  • Documentation: Adding notes to explain your work.

🧠 Important Concepts

  • Data integration is the process of combining data from different sources.
  • Automation reduces manual work and errors.
  • Flexibility is key – parameters and functions make queries adaptable.
  • Performance matters – always aim for fast queries.
  • Maintainability – document and structure your queries well.

📝 Step-by-Step Explanations

Combine Files from a Folder:

  1. Go to Data → Get Data → From File → From Folder.
  2. Browse to your folder and click OK.
  3. Power Query shows a list of files. Click "Combine & Transform Data".
  4. Select the sample file and click OK.
  5. Power Query combines all files automatically.

Create a Parameter:

  1. Go to Home → Manage Parameters → New Parameter.
  2. Name: "Year".
  3. Type: Number.
  4. Current Value: 2025.
  5. Click OK.

Use a Parameter in Filter:

  1. Select the column "Year".
  2. Click dropdown → Number Filters → Equals.
  3. In the value box, click the parameter icon (fx) and select "Year".

Create a Function from a Query:

  1. Right-click on the query in the Queries pane.
  2. Select "Create Function".
  3. Give it a name and click OK.

Optimise a Query:

  1. Remove unnecessary columns early.
  2. Filter rows as early as possible.
  3. Use "Keep Rows" instead of "Remove Rows" when it's fewer rows.

🌍 Real-life Examples

  • Retail chain: Combine daily sales from 100 stores into one report.
  • Education: Combine term results from all subjects into a single mark sheet.
  • Healthcare: Combine patient records from multiple hospitals.
  • Finance: Combine monthly budgets from all departments.

🇳🇬 Nigerian Examples

  • Bank: Combine daily transaction files from all branches in Nigeria.
  • Agriculture: Combine crop yield data from all states.
  • School: Combine exam scores from all primary schools in a local government.
  • Market: Combine sales data from different markets in Lagos.

🧸 Fun Examples Children Can Relate To

  • Game scores: Combine high scores from all your friends into one list.
  • School projects: Combine research from different websites into one document.
  • Pocket money: Combine weekly allowance records from the whole year.
  • Toys: Combine lists of toys from different siblings.

🏠 Everyday Examples

  • Grocery: Combine shopping lists from different stores.
  • Chores: Combine chore lists from all family members.
  • Photos: Combine photo file names into a single index.
  • Books: Combine book titles from different shelves.

👩‍🏫 Teacher Notes

  • Use the school story to relate to students.
  • Show live demo of combining files from a folder.
  • Have students create their own parameters.
  • Introduce functions gradually – they can be complex.
  • Emphasize the importance of error handling and documentation.

👪 Parent Tips

  • Help your child create a folder with multiple Excel files.
  • Let them practice combining files.
  • Show them how to use parameters to change results.
  • Encourage them to document their queries.

💡 Interesting Facts

  • Power Query can combine data from over 40 different data sources.
  • The "Combine Files" feature can handle hundreds of files at once.
  • Parameters can be used in M code to create dynamic queries.
  • Functions in Power Query are stored in the "M" language.
  • Power Query is used by many large companies to save hours of work.

🤔 Did You Know?

  • Did you know you can combine data from PDF files? Yes, Power Query can extract tables from PDFs!
  • Did you know you can combine data from web APIs? Power Query can connect to online services.
  • Did you know you can schedule a refresh so your data is always up-to-date?

🔔 Remember This

  • 📂 Combine files from a folder to save time.
  • 🔧 Parameters make your queries flexible.
  • 📦 Functions are reusable tools.
  • 🔗 Dependencies show how queries are connected.
  • ⚡ Optimise to make queries fast.
  • 🔄 Dynamic refresh keeps data current.
  • 📝 Document your work for future reference.

⚠️ Common Mistakes

  • Mistake 1: Forgetting to change the data type after combining.
  • Mistake 2: Not filtering before merging large files – slows down performance.
  • Mistake 3: Using wrong file extension – e.g., combining CSV with Excel files.
  • Mistake 4: Not handling errors – queries fail if a file is missing.
  • Mistake 5: Overcomplicating with too many steps – keep it simple.
  • Mistake 6: Not documenting – later you forget what you did.

✅ Best Practices

  • Always combine files from a folder to keep your process automatic.
  • Use parameters for values that might change (like year, region).
  • Create functions for repetitive tasks.
  • Optimise early: remove columns and filter rows as soon as possible.
  • Handle errors gracefully – use the "try" and "otherwise" logic.
  • Add comments to your M code for clarity.

📊 Illustrations

Flowchart: Combining Data from Folder

   [Start] 
      |
      V
   [Get Data from Folder]
      |
      V
   [Combine Files]
      |
      V
   [Clean & Transform]
      |
      V
   [Load to Excel]

Timeline: Data Integration Workflow

   1. Load Files   →   2. Combine   →   3. Clean   →   4. Transform
        ↓                  ↓              ↓              ↓
   5. Group/Pivot   →   6. Load   →   7. Refresh (optional)

Comparison: Manual vs Power Query Combine

FeatureManualPower Query
Time for 10 files30 minutes2 minutes
ErrorsHighLow
ReusabilityNoYes
AutomationNoYes

Comparison: Parameters vs Hard-coded Values

FeatureHard-codedParameter
Change valueEdit queryChange parameter
FlexibilityLowHigh
ReusabilityLowHigh

📌 End-of-Module Summary

Fantastic work! 🎉 You have completed Module 3. You now know how to:

  • Combine data from multiple files and folders.
  • Use parameters to make queries flexible.
  • Create and use functions.
  • Understand query dependencies.
  • Optimise query performance.
  • Set up dynamic refresh.
  • Build a complete workflow with error handling and documentation.

You are now a Power Query integration expert! You can handle data from anywhere and shape it perfectly.


❓ Frequently Asked Questions (10)

  1. Can I combine files with different structures? Yes, but you need to handle columns carefully.
  2. What file types can I combine? Excel, CSV, TXT, XML, JSON, and many more.
  3. How many files can I combine? Practically unlimited.
  4. Can I combine files from different folders? Yes, but it's easier if they are in one folder.
  5. What is a parameter used for? To make your query dynamic.
  6. Can I have multiple parameters? Yes, as many as you need.
  7. What is a function? A reusable set of steps.
  8. Can I share functions? Yes, you can copy them to other workbooks.
  9. How do I optimise a query? Remove unnecessary columns and filter early.
  10. Can I schedule a refresh? Yes, using Power BI or Excel's refresh options.

📝 Review Questions (15)

  1. What does "combine files" mean?
  2. How do you combine files from a folder?
  3. What is the "Combine Files" feature?
  4. What is a parameter?
  5. How do you create a parameter?
  6. How do you use a parameter in a query?
  7. What is a function?
  8. How do you create a function?
  9. What is a query dependency?
  10. Why is optimisation important?
  11. How do you optimise a query?
  12. What is dynamic refresh?
  13. What is a workflow?
  14. Why is error handling important?
  15. Why should you document your queries?

✏️ Fill-in-the-Blank

  1. Combining files brings data from different _______________ together. (sources)
  2. To combine files from a folder, use the "From _______________" option. (Folder)
  3. A _______________ is a value you can change easily. (parameter)
  4. A _______________ is a reusable set of steps. (function)
  5. Query _______________ show how queries are connected. (dependencies)
  6. To make a query faster, you _______________ it. (optimise)
  7. Dynamic refresh _______________ data automatically. (updates)
  8. A _______________ is a series of steps from start to finish. (workflow)
  9. _______________ handling manages problems gracefully. (Error)
  10. _______________ your queries helps others understand them. (Document)

✅ True or False

  1. You can only combine Excel files. (False – many types)
  2. Parameters make queries flexible. (True)
  3. Functions are not reusable. (False – they are reusable)
  4. Dependencies are not important. (False – they are important)
  5. Optimising makes queries faster. (True)
  6. Dynamic refresh updates data automatically. (True)
  7. A workflow has only one step. (False – many steps)
  8. Error handling is optional. (False – it's best practice)
  9. Documentation is a waste of time. (False – it's very useful)
  10. You cannot combine files from a folder. (False – you can)

🔘 Multiple Choice Questions

  1. Which option combines files from a folder?
    A) From Workbook B) From Folder C) From Database D) From Web
    Answer: B
  2. A parameter is used to:
    A) Delete data B) Make a query flexible C) Sort data D) Filter data automatically
    Answer: B
  3. A function is:
    A) A single step B) A reusable set of steps C) A type of data D) A filter
    Answer: B
  4. Query dependencies show:
    A) How queries are connected B) The size of data C) The file path D) The data type
    Answer: A
  5. Optimising a query means:
    A) Making it slower B) Making it faster C) Making it larger D) Deleting it
    Answer: B
  6. Dynamic refresh means:
    A) Data is deleted B) Data updates automatically C) Data is sorted D) Data is filtered
    Answer: B
  7. A workflow is:
    A) A single step B) A series of steps C) A type of file D) A parameter
    Answer: B
  8. Error handling helps with:
    A) Making errors bigger B) Managing problems C) Deleting errors D) Ignoring errors
    Answer: B
  9. Documentation is important for:
    A) Making it hard to understand B) Explaining your work C) Deleting data D) Sorting data
    Answer: B
  10. What is the first step in combining files from a folder?
    A) Clean data B) Get Data → From Folder C) Sort data D) Create parameter
    Answer: B
  11. Which is a best practice?
    A) Load all columns B) Filter early C) Skip error handling D) Never document
    Answer: B
  12. What can you combine in Power Query?
    A) Only Excel files B) Excel, CSV, XML, JSON C) Only CSV D) Only databases
    Answer: B
  13. How do you create a function?
    A) From a query B) From a parameter C) From a filter D) From a sort
    Answer: A
  14. What is the benefit of parameters?
    A) They make queries static B) They make queries dynamic C) They delete data D) They sort data
    Answer: B
  15. Why should you document your queries?
    A) To confuse others B) To help yourself and others C) To delete them D) To make them slow
    Answer: B

🔗 Matching Exercise

Column AColumn B
1. CombineA. Reusable steps
2. ParameterB. Dynamic value
3. FunctionC. Bring data together
4. OptimiseD. Make faster
5. WorkflowE. Series of steps

Answers: 1-C, 2-B, 3-A, 4-D, 5-E


📝 Short Answer Questions

  1. Explain how to combine files from a folder.
  2. What is a parameter and why is it useful?
  3. Describe the process of creating a function.
  4. Why is optimisation important in Power Query?
  5. What is dynamic refresh and how does it benefit you?

📖 Scenario-based Exercises

  1. Scenario: You have a folder with 12 monthly sales files (Jan-Dec). Describe how to combine them into one annual sales report using Power Query.
  2. Scenario: You need to combine files from 5 different branches, but each branch has a slightly different column order. How would you handle this?
  3. Scenario: You want your query to automatically include new files added to the folder. How would you set that up?

👥 Group Activity

Activity: In groups, create a folder with 5 different Excel files containing fictional sales data. Each group member creates one file. Then, use Power Query to combine all files, clean the data, and create a summary table. Present your results.


🧑 Individual Activity

Activity: Create a folder with 3 Excel files (e.g., Jan, Feb, Mar). Each file should have at least 10 rows of data. Use Power Query to combine them, then create a parameter for "Year" and filter the data accordingly. Save your query.


🗣️ Classroom Discussion Questions

  1. How would you handle combining files from different sources (Excel, CSV, text)?
  2. Why is it important to have a dynamic refresh?
  3. What challenges might you face when combining files?
  4. How can you ensure your query is optimised for large datasets?
  5. How would you document a complex query for your team?

🛠️ Mini Project

Project: Create a Power Query solution that combines data from at least 5 different Excel files in a folder. The files should have sales data for different regions. Clean the data, add a conditional column for "High" or "Low" sales, group by region, and create a summary. Load the final table into Excel. Document your steps.


💻 Practical Assignment

Assignment: Your teacher will provide a folder with 10 Excel files containing student grades. Your task:

  1. Combine all files using Power Query.
  2. Clean the data (remove blanks, trim spaces).
  3. Create a parameter for "Minimum Pass Mark" (default 70).
  4. Create a conditional column for "Pass/Fail".
  5. Group by subject to find average scores.
  6. Load the final report into Excel.
  7. Submit the Excel file with your queries.

🏆 Challenge Exercise

Challenge: Use Power Query to combine data from a folder of CSV files. But some files have extra columns. Write a function that cleans any file you give it, and then apply that function to all files while combining. This will test your skills in parameters and functions. Show your final combined table.


🔑 Quiz Answers

All answers are provided within each exercise section above.


🎁 Key Takeaways

  • Combining data from multiple files is easy with Power Query.
  • Parameters and functions make your queries flexible and reusable.
  • Optimising and documenting are essential for professional work.
  • Dynamic refresh keeps your data current.
  • You can build complete workflows to automate data processing.

📚 Preparation for Module 4

In Module 4, we will dive into Advanced Data Analysis with Power Query – we will learn about complex calculations, data modelling, and creating interactive dashboards. We will also explore how to use Power Query with Power BI. You are now ready to take on more complex data challenges. Keep practising and stay curious!


🎉 End of Module 3 – You are now a data combining champion! 🎉

5

Module Four

Module 4 · Power Query for Data Analysis Expert

📘 Module Four: Clean, Combine & Conquer – The Art of Shaping Data

Welcome, young data explorer! In this module, we will learn how to take messy, mixed‑up data and turn it into neat, tidy tables – just like arranging your toys in the right boxes. We call this “data cleaning” and “data shaping”. Power Query is like a magic kitchen where we chop, mix, and cook raw ingredients (data) into a delicious meal (clean information). By the end of this chapter, you will be able to fix errors, split names, join tables, and make your data ready for answers.

🎯 Learning Objectives

  • Explain why data must be cleaned before analysis.
  • Use Power Query to remove empty rows and fix spelling mistakes.
  • Split one column into two (like separating first name and last name).
  • Merge two tables together using a common column.
  • Change data types (text, number, date) correctly.
  • Use the “Fill Down” feature to copy values.
  • Create custom columns with simple formulas.

📖 Warm‑up Story: Grandma’s Spice Mix

Ade loves helping his grandma in the kitchen. One day, Grandma said, “Ade, please mix the spices for the jollof rice – but each spice is in a different bag, and some bags are not labelled!” Ade found bags with “salt”, “pepper”, “curry”, and one bag just said “????”. He had to sort, taste, and mix everything carefully. When he finished, the jollof rice was perfect!
Data is like those spices. It comes from different places, sometimes with missing labels. Power Query is your mixing bowl – it helps you sort, rename, and blend everything so you can cook up the right answers!

📚 Main Lessons

Lesson 1: What is “Data Cleaning”?

Definition: Data cleaning means fixing mistakes and removing things that don’t belong in your data table.

Why important: If your data is dirty, your answers will be wrong – like using salt instead of sugar in a cake!

Simple explanation: Imagine your school’s list of students has some names spelled wrong and some blank rows. Cleaning means you correct the names and delete the empty rows.

Real‑life example: A shopkeeper checks his sales list – some prices are missing, so he fills them in.

School example: The class register has two “Mary” entries – one is Mary A., the other Mary B. You fix it.

Home example: Your mom’s grocery list has “milk” written twice – you cross out the extra one.

Nigerian example: A local market seller records sales on paper. Some numbers are faded; she rewrites them clearly before typing into Excel.

Dirty data   →   Clean data
"2,0"        →   20
"N/A"        →   (empty)
"LAGOS"      →   "Lagos"

Mini summary: Cleaning = fixing errors and removing clutter so your data tells the truth.

Lesson 2: Removing Empty Rows and Columns

Definition: Empty rows are blank lines in your table. Empty columns have no data at all.

Why important: They waste space and can confuse Power Query.

Simple explanation: Like having empty chairs in a classroom – you don’t count them when taking attendance.

Real‑life example: A phone book with blank pages – you skip them.

School example: Your teacher’s mark sheet has empty rows for absent students – she removes them.

Home example: A list of chores with a blank line – you delete it.

Nigerian example: A Lagos bus conductor’s daily passenger count may have blank rows for trips that didn’t happen; he removes them.

How to in Power Query: Home → Remove Rows → Remove Blank Rows.

Before:
Row1: Ade, 10
Row2: (blank)
Row3: Bola, 12

After:
Row1: Ade, 10
Row2: Bola, 12

Mini summary: Blank rows are like empty seats – take them out!

Lesson 3: Fixing Spelling and Capital Letters

Definition: This means making sure all names and words are spelled the same way and have proper capital letters.

Why important: “LAGOS” and “lagos” are the same city – but the computer thinks they are different if we don’t fix them.

Simple explanation: Like writing your name with a capital letter – “Ade” not “ade”.

School example: Your class list has “John” and “jon” – you change both to “John”.

Home example: Your dad’s contact list has “Mum” and “mum” – you make them both “Mum”.

Nigerian example: Abuja is sometimes written “abuja” – we change it to “Abuja”.

Before: "ikeja", "IKEJA", "Ikeja"
After:  "Ikeja", "Ikeja", "Ikeja"

Mini summary: Always use the same spelling and capitals so your data stays neat.

Lesson 4: Splitting Columns

Definition: Splitting means taking one column and dividing it into two columns – like separating first name and last name.

Why important: It helps you sort by last name or first name separately.

Simple explanation: Like separating your full name “Ade Ojo” into “Ade” and “Ojo”.

Real‑life example: A list of customers has “Mr. Ade Ojo” – you split into title, first name, last name.

School example: The teacher has “Maryam Bello” – split into “Maryam” and “Bello”.

Home example: “Chicken and rice” – split into “Chicken” and “rice”.

Nigerian example: “Lagos, Nigeria” – split into “Lagos” and “Nigeria”.

How to: Transform → Split Column → By Delimiter (e.g., space or comma).

FullName       →   FirstName   LastName
Ade Ojo        →   Ade         Ojo
Funke Ade      →   Funke       Ade

Mini summary: Split separates data into smaller pieces for better handling.

Lesson 5: Merging Columns

Definition: Merging is the opposite of splitting – you combine two columns into one.

Why important: Sometimes you want a full name instead of separate first and last.

Simple explanation: Like putting two puzzle pieces together to see the whole picture.

School example: You have “First” and “Last” – merge to “Full Name”.

Home example: “Street” and “City” merge to “Address”.

Nigerian example: “State” and “LGA” merge to “Location”.

First   Last   →   FullName
Ade     Ojo    →   Ade Ojo

Mini summary: Merging puts pieces back together when needed.

Lesson 6: Changing Data Types (Text, Number, Date)

Definition: Data type tells Power Query what kind of data is in a column – words (text), numbers, or dates.

Why important: You can’t add text like “ten” to a number – the computer needs to know.

Simple explanation: Like sorting toys into boxes – words in one box, numbers in another.

Real‑life example: “1,000” as text vs. 1000 as a number – you can only add numbers.

School example: Marks are numbers, names are text – don’t mix them.

Home example: Date of birth is a date; age is a number.

Nigerian example: “₦500” is text (has symbol) but we need the number 500 to add prices.

Text: "10"  →  Number: 10
Date: "01/01/2025" → Date type

Mini summary: Always set the right data type so Power Query understands your data.

Lesson 7: Fill Down – Copying Values Down

Definition: Fill Down takes a value from a cell and copies it into the empty cells below it.

Why important: In some tables, the value is only written once, but it applies to many rows.

Simple explanation: Like when your teacher says “Class 4” at the top – it means all students are in Class 4.

School example: A register with “Year 5” at the top – fill down so every row has “Year 5”.

Home example: A grocery list with “Store: Shoprite” at the top – fill down for all items.

Nigerian example: A list of students from “Lagos State” – fill down so all rows show Lagos.

Before:           After:
Region            Region
North             North
(blank)           North
South             South
(blank)           South

Mini summary: Fill Down saves time – copy once, paste many!

Lesson 8: Creating Custom Columns

Definition: A custom column is a new column you build using a formula, like combining or calculating.

Why important: It lets you create new information from existing columns.

Simple explanation: Like making a fruit salad – you take apples and oranges and mix them into a new dish.

School example: You have “Maths” and “English” marks – create a “Total” column by adding them.

Home example: You have “Price” and “Quantity” – create “Total Cost” = Price × Quantity.

Nigerian example: You have “Naira” and “Kobo” – create “Total Amount” in Naira.

Price   Quantity   →   TotalCost
100     3          →   300
200     2          →   400

Mini summary: Custom columns let you create new facts from your data.

Lesson 9: Merging Tables (Like Joining Friends)

Definition: Merging tables means bringing two tables together based on a common column (like a student ID).

Why important: Sometimes information about the same thing is in two places – merging brings it together.

Simple explanation: Like having your friends’ names in one list and their phone numbers in another – you combine them.

School example: Table 1: Student ID and Name. Table 2: Student ID and Marks. Merge to get Name + Marks.

Home example: Table 1: Item names. Table 2: Prices. Merge to see item + price.

Nigerian example: Table 1: LGA names. Table 2: LGA population. Merge to get LGA + population.

Table1 (ID, Name)   +   Table2 (ID, Age)  →  Merged (ID, Name, Age)
1, Ade                   1, 10             →  1, Ade, 10
2, Bola                  2, 12             →  2, Bola, 12

Mini summary: Merging joins two tables using a shared key column.

Lesson 10: Pivot and Unpivot – Changing Table Shape

Definition: Pivot turns rows into columns. Unpivot turns columns into rows.

Why important: Sometimes data is easier to read in a different shape.

Simple explanation: Like turning a line of people into a circle – same people, different arrangement.

School example: You have subjects as columns – pivot to make subjects rows.

Home example: You have months as columns – pivot to make months rows for easier charting.

Nigerian example: Sales data with months as columns – pivot to analyse by month.

Before (wide):
Student  Maths  English
Ade      80     70
After (long):
Student  Subject  Marks
Ade      Maths    80
Ade      English  70

Mini summary: Pivot and unpivot change how your table looks, not the data itself.

Lesson 11: Replacing Values

Definition: Replacing means swapping one value with another – like changing “N/A” to blank.

Why important: It standardises data so everything is consistent.

Simple explanation: Like changing “Mum” to “Mother” everywhere.

School example: Replace “Abs” with “Absent”.

Home example: Replace “fridge” with “refrigerator”.

Nigerian example: Replace “LAG” with “Lagos”.

Before: "LAG", "Lagos", "lagos"
After:  "Lagos", "Lagos", "Lagos"

Mini summary: Replace fixes inconsistent words quickly.

Lesson 12: Keeping Only Important Columns

Definition: You can choose to remove columns you don’t need.

Why important: Fewer columns make it easier to focus on what matters.

Simple explanation: Like choosing only your favourite toys to play with.

School example: A report card has many columns – keep only Name and Total.

Home example: Shopping list with price, quantity, and aisle – keep only price and quantity.

Nigerian example: Population data with many details – keep only State and Population.

Before: ID, Name, Age, Grade, Teacher
After:  Name, Grade   (removed ID, Age, Teacher)

Mini summary: Keep only the columns that answer your question.

Lesson 13: Sorting and Filtering Rows

Definition: Sorting arranges rows in order (A→Z, smallest→largest). Filtering shows only rows that meet a condition.

Why important: It helps you find the top scores or see only a specific group.

Simple explanation: Like lining up from shortest to tallest (sorting) or only picking kids who wear glasses (filtering).

School example: Sort marks from highest to lowest; filter to see only students with marks above 80.

Home example: Sort grocery list alphabetically; filter to show only fruits.

Nigerian example: Sort states by population; filter to show only states in the South‑South.

Sort: 5, 3, 9 → 3, 5, 9
Filter: [10, 20, 30] > 20 → [30]

Mini summary: Sorting and filtering help you find the data you need quickly.

Lesson 14: Using the “Group By” Feature

Definition: Group By takes rows with the same value and summarises them – like counting or summing.

Why important: It gives you totals by category – like total sales per region.

Simple explanation: Like grouping your toys by colour and counting how many of each colour.

School example: Group students by class and count how many in each class.

Home example: Group shopping items by category (fruits, vegetables) and count.

Nigerian example: Group sales by state and find total sales per state.

Before: (Ade, Lagos), (Bola, Lagos), (Tunde, Abuja)
After Group By State:
Lagos: 2
Abuja: 1

Mini summary: Group By summarises data by categories.

Lesson 15: Undo and Redo – Fixing Mistakes

Definition: Undo takes back your last step. Redo puts it back again.

Why important: You can experiment without fear – if you make a mistake, just undo!

Simple explanation: Like erasing a wrong answer and writing it again.

School example: You delete a column by mistake – undo brings it back.

Home example: You change “rice” to “beans” – undo changes it back.

Nigerian example: You replaced all “Lagos” with “Abuja” – undo to fix.

How to: Use the “Undo” button or Ctrl+Z.

Mini summary: Undo is your safety net – always available!

🔑 Key Vocabulary (simple definitions)

  • Data cleaning: Fixing errors and removing useless parts in data.
  • Column: A vertical list of values (like a column in a building).
  • Row: A horizontal line of data (like a row of seats).
  • Delimiter: A symbol that separates pieces, like a space or comma.
  • Merge: To combine two tables into one.
  • Pivot: Turning rows into columns.
  • Unpivot: Turning columns into rows.
  • Data type: Tells the computer if data is text, number, or date.
  • Fill Down: Copies a value from above to empty cells below.
  • Group By: Summarises rows that share a common value.

🧠 Important Concepts

  • Garbage in, garbage out: If you put dirty data in, you get wrong answers out.
  • Consistency: Always use the same spelling and format.
  • Data integrity: Keeping data accurate and reliable.
  • Normalisation: Organising data to avoid duplication.

📝 Step‑by‑Step Explanations

How to Split a Column

  1. Select the column you want to split.
  2. Click “Transform” → “Split Column” → “By Delimiter”.
  3. Choose the delimiter (e.g., space, comma).
  4. Choose where to split (leftmost, rightmost, or all).
  5. Click OK – now you have two columns!

How to Merge Two Tables

  1. Click “Home” → “Merge Queries”.
  2. Select the second table.
  3. Choose the common column (like Student ID) in both tables.
  4. Select join type (usually “Left Outer” to keep all from the first table).
  5. Click OK – then expand the new column to bring in the fields.

🌍 Real‑life Examples

  • Bank: Banks clean customer data to send the right messages.
  • Hospital: Doctors clean patient records to avoid medicine errors.
  • Supermarket: Cleans sales data to know which products sell most.

🇳🇬 Nigerian Examples

  • INEC voter list: Clean names and addresses to avoid duplicates.
  • Nigerian Census: Combine state and LGA data for population counts.
  • Market traders: Merge daily sales from different stalls.

🧸 Fun Examples

  • Your collection of 100 toy cars – clean by removing broken ones.
  • Your friend list – merge with birthdays to know whom to wish.
  • Your Pokémon cards – group by type (fire, water).

🏠 Everyday Examples

  • Cleaning your school bag by removing old papers.
  • Sorting your books by subject.
  • Combining two lists of chores into one.

👩‍🏫 Teacher Notes

  • Encourage students to practice each operation on sample data.
  • Use real school data (like marks) to make it relevant.
  • Emphasise that mistakes are part of learning – use undo.

👨‍👩‍👧 Parent Tips

  • Help your child create a simple data table (e.g., weekly allowance).
  • Show them how to correct spelling errors in a list.
  • Make it a game – “find and fix” the dirty data!

💡 Interesting Facts

  • Data scientists spend up to 80% of their time cleaning data!
  • Power Query can clean millions of rows in seconds.
  • Clean data helps predict traffic, weather, and even disease spread.

🤔 Did You Know?

  • Power Query was originally called “Data Explorer”.
  • You can connect Power Query to websites and clean live data.

🧷 Remember This

  • Always clean your data before analysing.
  • Check data types – text, number, date.
  • Use split and merge when needed.
  • Group By gives you summaries.

⚠️ Common Mistakes

  • Forgetting to change data type – adding text as numbers.
  • Not removing blank rows – they affect totals.
  • Merging tables without a matching column.
  • Using the wrong delimiter when splitting.

✅ Best Practices

  • Always keep a copy of the original data.
  • Name your steps clearly in Power Query.
  • Use “Remove Duplicates” to keep only unique rows.
  • Preview your data after every step.

🖼️ Illustrations

Data Cleaning Process
+-------------------+
|  Dirty Data       |
|  (spelling errors,|
|   blanks, mixed)  |
+--------+----------+
         |
         V
+--------+----------+
|  Clean Steps      |
|  - Remove blanks  |
|  - Fix spelling   |
|  - Split columns  |
+--------+----------+
         |
         V
+--------+----------+
|  Clean Data       |
|  (neat, correct,  |
|   ready to use)   |
+-------------------+
Split Column – before and after
+-----------------+     +-----------------+-----------------+
| FullName        |     | FirstName       | LastName        |
+-----------------+     +-----------------+-----------------+
| Ade Ojo         |  →  | Ade             | Ojo             |
+-----------------+     +-----------------+-----------------+

📊 Comparison Tables

OperationUseExample
SplitSeparate one column into twoFullName → First, Last
MergeCombine two columns into oneFirst + Last → FullName
Group BySummarise by categoryCount students per class
PivotRows to columnsSubject names as columns

📌 End‑of‑Module Summary

In this module, we learned how to make our data beautiful and useful. We removed blank rows, fixed spelling, split and merged columns, changed data types, used Fill Down, created custom columns, and even merged tables. We also explored Pivot, Unpivot, Group By, and sorting. Remember – clean data leads to correct answers. Always check your data types and keep only what you need. You are now ready to turn messy data into a clear story!

❓ Frequently Asked Questions

  1. What is the first step in cleaning data? – Look for blank rows and remove them.
  2. How do I split a column? – Use “Split Column” by delimiter like space.
  3. What is a delimiter? – A symbol that separates parts, e.g., comma, space.
  4. Why change data types? – So Power Query knows if it’s text, number, or date.
  5. What does Fill Down do? – Copies a value from above to empty cells below.
  6. How do I merge two tables? – Use “Merge Queries” and choose a common column.
  7. What is Group By? – Summarises rows with the same value (e.g., count by state).
  8. Can I undo a step? – Yes, click Undo or press Ctrl+Z.
  9. What is Pivot? – Turns rows into columns.
  10. What is the most important rule? – Always clean your data before analysing!

📝 Review Questions

  1. What does data cleaning mean?
  2. How do you remove blank rows in Power Query?
  3. Why is it important to fix capital letters?
  4. Name two ways to split a column.
  5. What is the difference between merge and split?
  6. List three data types.
  7. When would you use Fill Down?
  8. What is a custom column?
  9. How do you join two tables in Power Query?
  10. What does Group By do?
  11. Give an example of Pivot.
  12. Why should you keep only important columns?
  13. What is the shortcut for Undo?
  14. What is a delimiter? Give two examples.
  15. Why is clean data better than dirty data?

✍️ Fill‑in‑the‑Blank

  1. Data cleaning means fixing _______ and removing useless parts.
  2. _______ copies a value from above to empty cells below.
  3. _______ tells the computer if data is text, number, or date.
  4. _______ combines two tables using a common column.
  5. _______ turns rows into columns.

✅ True or False

  1. Blank rows are helpful for analysis. (False)
  2. You should always change data type before adding numbers. (True)
  3. Merge is the same as split. (False)
  4. Fill Down copies data from the row below. (False – it copies from above)
  5. Pivot turns rows into columns. (True)

🔘 Multiple Choice Questions

  1. Which operation removes blank rows?
    a) Split b) Remove Rows c) Merge d) Pivot
    Answer: b
  2. Which is NOT a data type?
    a) Text b) Number c) Colour d) Date
    Answer: c
  3. What does Fill Down do?
    a) Copies value from above b) Copies from below c) Splits data d) Merges data
    Answer: a
  4. Which is used to combine two tables?
    a) Split b) Merge c) Pivot d) Group By
    Answer: b
  5. Group By is used to …
    a) Split columns b) Summarise categories c) Fix spelling d) Change types
    Answer: b
  6. What is a delimiter?
    a) A number b) A separator symbol c) A data type d) A column
    Answer: b
  7. Which turns rows into columns?
    a) Unpivot b) Pivot c) Merge d) Fill Down
    Answer: b
  8. Which shortcut is Undo?
    a) Ctrl+Z b) Ctrl+C c) Ctrl+V d) Ctrl+X
    Answer: a
  9. Why change data type?
    a) For colour b) So Power Query understands c) To delete rows d) To split columns
    Answer: b
  10. Which is a best practice?
    a) Keep dirty data b) Keep a copy of original c) Never undo d) Ignore blanks
    Answer: b
  11. What does Unpivot do?
    a) Turns columns into rows b) Turns rows into columns c) Merges tables d) Sorts data
    Answer: a
  12. Which column operation separates first and last name?
    a) Merge b) Split c) Group By d) Fill Down
    Answer: b
  13. What is a custom column?
    a) A column you create with a formula b) A pre‑made column c) A blank column d) A column with errors
    Answer: a
  14. Which is NOT a cleaning step?
    a) Fix spelling b) Remove blanks c) Add random data d) Change types
    Answer: c
  15. What should you do before analysing?
    a) Clean data b) Delete everything c) Merge all tables d) Pivot everything
    Answer: a

🔗 Matching Exercises

Match the term with its description:

TermDescription
1. SplitA. Combine two tables
2. MergeB. Separate one column into two
3. PivotC. Turns rows into columns
4. Group ByD. Summarise by category

Answers: 1-B, 2-A, 3-C, 4-D

✏️ Short Answer Questions

  1. Explain why you should remove blank rows before analysis.
  2. Describe the steps to split a column by space.
  3. What is the difference between Merge and Group By?
  4. Give two examples of data types.
  5. Why is it useful to keep a copy of the original data?

📖 Scenario‑based Exercises

Scenario 1: You have a list of 100 students with names like “Ade Ojo”, “Bola”, “Chidi Eze” (missing last name). How would you clean this? (Answer: split full name where possible, leave missing as blank or fix manually.)

Scenario 2: Your teacher gave you two tables – one with student IDs and names, another with student IDs and test scores. How can you combine them? (Answer: merge on Student ID.)

👥 Group Activity

In small groups, create a messy data table with at least 10 rows and 4 columns (include spelling errors, blanks, mixed capitals). Exchange tables with another group and clean each other’s data using the steps learned.

🧑‍🎓 Individual Activity

Open Excel or Power Query (if available). Take the class attendance list and clean it: remove empty rows, fix names, and change the date column to Date type.

🗣️ Classroom Discussion Questions

  1. Why is clean data important for making decisions?
  2. What happens if you forget to change a data type?
  3. When would you use Pivot instead of Group By?

🛠️ Mini Project

Collect data from your classmates: Name, Age, Favourite Subject, and Score in Maths (out of 100). Type it into Excel. Use Power Query to: (1) Remove blank rows, (2) Split name into first and last, (3) Change Age to number, (4) Sort by Score descending. Show your clean table.

💻 Practical Assignment

Download a sample dataset from the internet (or use a provided one). Clean it using at least 5 different operations (remove blanks, fix capitals, split, merge, change type). Submit the cleaned file and a short report of what you did.

🏆 Challenge Exercise

You have a table with “Product”, “Region”, “Sales”, “Quarter”. Use Power Query to: (1) Unpivot the quarters, (2) Group by Region to find total sales, (3) Merge with a product category table (provided) to add category information. This is tricky – try your best!

🔍 Quiz Answers

Fill‑in‑the‑Blank: 1. errors 2. Fill Down 3. Data type 4. Merge 5. Pivot

True or False: 1-F, 2-T, 3-F, 4-F, 5-T

Multiple Choice: 1-b, 2-c, 3-a, 4-b, 5-b, 6-b, 7-b, 8-a, 9-b, 10-b, 11-a, 12-b, 13-a, 14-c, 15-a

🎁 Key Takeaways

  • Clean data is the foundation of good analysis.
  • Power Query offers many tools to fix and shape data.
  • Always check data types and remove blanks.
  • Practice makes perfect – keep experimenting!

🔜 Preparation for Module Five

In the next module, we will dive into “Data Transformation with M Language”. You will learn how to write simple code to automate all the cleaning steps we did manually. Get ready to become a Power Query wizard!

Note: This is Module Four. In our course, Module Three covers “Connecting to Data Sources”. We will now transition to Module Five, but you have mastered the art of cleaning – well done!

6

Module Five

Module 5 · Certified Power Query for Data Analysis Expert

📘 Module Five: The Magic of M Language – Writing Your First Power Query Code

Hello, young data wizard! So far, we have been using buttons and menus to clean and shape our data. But did you know that behind every click, Power Query writes a little language called “M”? M is like a recipe for data. In this module, we will open the kitchen and look at the recipe itself. We will learn to read and write simple M code. Don’t worry – it is easier than you think! Think of M as giving instructions to a very smart robot. You tell it step by step what to do, and it does it perfectly every time.

🎯 Learning Objectives

  • Understand what M language is and why it is used.
  • Read simple M expressions and know what they mean.
  • Write your own M code to clean data.
  • Use the “Advanced Editor” to see and change M code.
  • Understand variables and steps in M.
  • Create functions to repeat tasks.
  • Use common M functions like Table.SelectRows, Table.AddColumn, and Table.TransformColumnTypes.
  • Combine steps using the “let” and “in” structure.

📖 Warm‑up Story: The Robot Chef

Chidi loves cooking, but he is lazy. He wishes he had a robot that could chop, stir, and fry all by itself. One day, his uncle gives him a small robot. But the robot only follows written instructions. Chidi writes: “Step 1: Peel the yam. Step 2: Cut into cubes. Step 3: Fry until golden.” He places the paper in the robot, and the robot does exactly what he wrote!
M language is like those written instructions. Every click in Power Query creates a line of M code. When you learn M, you become the robot’s boss – you can write your own instructions and make the robot do exactly what you want, faster than using buttons!

📚 Main Lessons

Lesson 1: What is M Language?

Definition: M is a programming language used in Power Query to clean, combine, and transform data.

Why important: M gives you superpowers – you can do things that buttons cannot.

Simple explanation: M is like a recipe for data. You list steps, and Power Query cooks them in order.

Real‑life example: A baker writes a recipe – mix flour, add eggs, bake. M does the same for data.

School example: You write steps to solve a math problem – M writes steps to clean data.

Home example: You write a to‑do list for chores – M writes a to‑do list for data.

Nigerian example: A caterer writes steps to prepare jollof rice – M writes steps to prepare data.

// This is M code!
let
    Source = Excel.Workbook(...),
    Sheet1 = Source{...}[Data],
    Cleaned = Table.RemoveRows(Sheet1, ...)
in
    Cleaned

Mini summary: M is the language that tells Power Query what to do.

Lesson 2: Where to Find M Code

Definition: The Advanced Editor is where you can see and edit M code.

Why important: You can copy, paste, and write your own M code there.

Simple explanation: Like opening the hood of a car to see the engine.

Real‑life example: In a restaurant, you can watch the chef cook – the Advanced Editor shows you the cooking steps.

School example: Your teacher shows you the answer key – the Advanced Editor shows you the code.

Home example: You open your toy box to see all your toys – the Advanced Editor shows all your steps.

Nigerian example: A mechanic opens the car bonnet – you open the Advanced Editor.

How to: Home → Advanced Editor (or View → Advanced Editor).

let
    // All your steps appear here
    Source = ...
in
    Source

Mini summary: Advanced Editor is your window to the M code.

Lesson 3: The let ... in Structure

Definition: “let” is where you define your steps. “in” is where you tell Power Query what to output.

Why important: This is the basic building block of every M script.

Simple explanation: “let” = list your tasks, “in” = show the final result.

Real‑life example: Your mom says “let me gather ingredients, then in the pot I cook.”

School example: “Let me read the question, then in my answer book I write.”

Home example: “Let me pick my clothes, then in the bag I pack.”

Nigerian example: “Let me buy the tomatoes, then in the stew I put them.”

let
    Step1 = 5,
    Step2 = Step1 + 3
in
    Step2   // result is 8

Mini summary: “let” holds steps, “in” returns the final value.

Lesson 4: Variables – Naming Your Steps

Definition: A variable is a name you give to a value or a step, like “CleanedData”.

Why important: Variables help you remember what each step does.

Simple explanation: Like giving a name to your pet – you can call it by name later.

Real‑life example: You name your backpack “BlueBag” – then you say “Put books in BlueBag”.

School example: You name a math answer “Result” – then use it in another equation.

Home example: You name your toy box “ToyChest” – you know where to find toys.

Nigerian example: You name your market bag “Ade’s Bag” – everyone knows it’s yours.

let
    MyNumber = 10,
    MyResult = MyNumber * 2
in
    MyResult   // 20

Mini summary: Variables are like labels for your data steps.

Lesson 5: Comments – Writing Notes in M

Definition: Comments are notes you write for yourself (or others) that do not affect the code.

Why important: They help you remember what your code does.

Simple explanation: Like writing a note on your hand to remind you of something.

Real‑life example: A cook writes “add salt” on a sticky note.

School example: You write “this is the formula for area” in your notebook.

Home example: You put a sticky note on the fridge saying “buy milk”.

Nigerian example: A trader writes “price = 200” on a board.

// This is a single-line comment
let
    Step1 = 5,  // This is also a comment
    Step2 = Step1 + 3
in
    Step2

Mini summary: Comments are notes that help you and others understand your code.

Lesson 6: Common M Functions – Table.AddColumn

Definition: Table.AddColumn creates a new column in your table.

Why important: It lets you add calculated values, just like we did with custom columns before.

Simple explanation: Like adding a new subject to your report card.

Real‑life example: A shop adds a “Discount” column to a sales table.

School example: You add a “Total” column to your marks.

Home example: You add a “Price per kg” column to a grocery list.

Nigerian example: Add a “VAT” column to a price list.

let
    Source = Table.FromRecords({[Name="Ade", Score=80]}),
    NewCol = Table.AddColumn(Source, "Grade", each if [Score] >= 70 then "A" else "B")
in
    NewCol

Mini summary: Table.AddColumn creates new columns using formulas.

Lesson 7: Table.TransformColumnTypes

Definition: This function changes the data type of one or more columns.

Why important: It ensures numbers are numbers and dates are dates.

Simple explanation: Like changing a label from “text” to “number”.

School example: Change “10” (text) to 10 (number) so you can add marks.

Home example: Change “01/01/2025” to a date type.

Nigerian example: Change “₦500” to a number 500 for calculations.

let
    Source = Table.FromRecords({[Price="500"]}),
    Changed = Table.TransformColumnTypes(Source, {{"Price", type number}})
in
    Changed

Mini summary: TransformColumnTypes fixes data types.

Lesson 8: Table.SelectRows – Filtering Data

Definition: This function keeps only rows that meet a condition.

Why important: It helps you focus on specific data, like only students with marks above 80.

Simple explanation: Like picking only red balls from a box of coloured balls.

School example: Keep only students who passed.

Home example: Keep only items that cost less than 100.

Nigerian example: Keep only states in the South‑South region.

let
    Source = Table.FromRecords({[Name="Ade", Score=90], [Name="Bola", Score=65]}),
    Filtered = Table.SelectRows(Source, each [Score] >= 70)
in
    Filtered   // only Ade remains

Mini summary: SelectRows filters data based on a condition.

Lesson 9: Table.RemoveColumns – Dropping Columns

Definition: This function removes columns you don’t need.

Why important: It reduces clutter and makes your table easier to read.

Simple explanation: Like taking out toys you don’t play with from your toy box.

School example: Remove the “Teacher” column if you only need student names.

Home example: Remove the “Aisle” column from a shopping list.

Nigerian example: Remove the “LGA” column if you only need state.

let
    Source = Table.FromRecords({[Name="Ade", Age=10, Teacher="Mr. Smith"]}),
    Removed = Table.RemoveColumns(Source, {"Teacher"})
in
    Removed   // only Name and Age remain

Mini summary: RemoveColumns gets rid of unwanted columns.

Lesson 10: Table.Combine – Merging Tables in M

Definition: Table.Combine stacks two tables on top of each other (like appending).

Why important: It combines rows from different tables with the same columns.

Simple explanation: Like putting two piles of books together.

School example: Combine Class A marks and Class B marks into one list.

Home example: Combine your grocery list with your sister’s grocery list.

Nigerian example: Combine sales data from two markets.

let
    Table1 = Table.FromRecords({[Name="Ade", Score=80]}),
    Table2 = Table.FromRecords({[Name="Bola", Score=90]}),
    Combined = Table.Combine({Table1, Table2})
in
    Combined   // two rows

Mini summary: Table.Combine stacks rows from multiple tables.

Lesson 11: Table.Join – Merging Tables (like SQL JOIN)

Definition: Table.Join combines two tables based on a common column.

Why important: It brings together data from different sources using a key.

Simple explanation: Like matching people with their phone numbers using their names.

School example: Join student names with their scores using Student ID.

Home example: Join product names with prices using Product Code.

Nigerian example: Join LGA names with population using LGA Code.

let
    Table1 = Table.FromRecords({[ID=1, Name="Ade"], [ID=2, Name="Bola"]}),
    Table2 = Table.FromRecords({[ID=1, Age=10], [ID=2, Age=12]}),
    Joined = Table.Join(Table1, "ID", Table2, "ID", JoinKind.LeftOuter)
in
    Joined   // ID, Name, Age

Mini summary: Table.Join merges tables using a key column.

Lesson 12: Using “each” and “_” (underscore)

Definition: “each” is a shortcut for writing a function that applies to every row. “_” represents the current row.

Why important: They save you typing and make code shorter.

Simple explanation: “each” means “for every row, do this”. “_” means “this row”.

Real‑life example: “Each student, write your name” – you use “_” to refer to that student.

School example: “Each answer, check if it’s correct.”

Home example: “Each item, add price.”

Nigerian example: “Each market, count customers.”

// Add 10 to every score
Table.AddColumn(Source, "NewScore", each [Score] + 10)
// Same as: each _[Score] + 10

Mini summary: “each” and “_” make it easy to work with every row.

Lesson 13: Creating Your Own Functions

Definition: A function is a block of code that does a specific task and can be reused.

Why important: Instead of writing the same code many times, you write it once and call it.

Simple explanation: Like a recipe for “eggs” – you can use it to make breakfast many times.

School example: A function to calculate average – use it for maths, English, etc.

Home example: A function to convert naira to dollars – use it whenever needed.

Nigerian example: A function to add VAT – use it for any product.

let
    AddTen = (x) => x + 10,
    Result = AddTen(5)   // 15
in
    Result

Mini summary: Functions are reusable code blocks.

Lesson 14: Handling Errors in M

Definition: Errors happen when something goes wrong – like trying to add text to a number.

Why important: Knowing how to handle errors makes your code strong and safe.

Simple explanation: Like wearing a helmet when riding a bike – it protects you.

School example: If a student’s score is missing, use 0 instead.

Home example: If an item has no price, set it to “free”.

Nigerian example: If a state name is missing, write “Unknown”.

// Using try ... otherwise
let
    SafeDivide = (a, b) => if b = 0 then 0 else a / b
in
    SafeDivide(10, 0)   // returns 0 instead of error

Mini summary: Error handling keeps your code from breaking.

Lesson 15: The Power of “record” and “list”

Definition: A record is like a row (with column names and values). A list is a collection of values.

Why important: Many M functions use records and lists.

Simple explanation: A record is like a student’s report card (Name, Score). A list is like a bag of marbles.

School example: Record = {Name="Ade", Score=80}. List = {80, 90, 70}.

Home example: Record = {Item="Bread", Price=200}. List = {200, 150, 300}.

Nigerian example: Record = {State="Lagos", Population=20M}. List = {"Lagos", "Abuja", "Kano"}.

let
    MyRecord = [Name="Ade", Score=80],
    MyList = {10, 20, 30},
    FirstItem = MyList{0}   // 10
in
    FirstItem

Mini summary: Records hold row data; lists hold sequences of values.

🔑 Key Vocabulary (simple definitions)

  • M language: The programming language behind Power Query.
  • Advanced Editor: The window where you can write or edit M code.
  • Variable: A name given to a value or step.
  • Comment: A note in the code that is not executed.
  • Function: A block of code that performs a specific task.
  • Record: A set of fields (like a row in a table).
  • List: A collection of values (like an array).
  • let ... in: The structure that holds steps and returns a result.
  • each: A keyword that applies an operation to every row.
  • Error handling: Ways to prevent code from crashing.

🧠 Important Concepts

  • Case sensitivity: M is case‑sensitive – “Name” is different from “name”.
  • Data types in M: Text, Number, Date, Logical (true/false).
  • Reusability: Write once, use many times with functions.
  • Immutability: In M, data is not changed; new data is created from old.

📝 Step‑by‑Step Explanations

How to add a custom column using M

  1. Open the Advanced Editor (Home → Advanced Editor).
  2. Find the step just before you want to add the column.
  3. Write: NewStep = Table.AddColumn(PreviousStep, "NewColumnName", each [OldColumn] * 2)
  4. Change the “in” line to return NewStep.
  5. Click Done – your new column appears!

How to filter rows using M

  1. In Advanced Editor, after your source step, add: Filtered = Table.SelectRows(Source, each [Score] >= 70)
  2. Change the “in” line to Filtered.
  3. Done – only rows with Score ≥ 70 remain.

🌍 Real‑life Examples

  • Bank: Uses M to filter fraudulent transactions.
  • Hospital: Uses M to combine patient records from different departments.
  • Online Shop: Uses M to add tax columns to products.

🇳🇬 Nigerian Examples

  • NIMC: Cleans and merges citizen data using M.
  • NAFDAC: Uses M to transform product registration data.
  • Local markets: Traders can use M to combine sales from different days.

🧸 Fun Examples

  • Your toy collection – M can add a “Price” column and filter toys under 500.
  • Your friend list – M can combine two lists of friends.
  • Your scores – M can add a “Pass/Fail” column.

🏠 Everyday Examples

  • Creating a shopping list with totals.
  • Combining homework lists from two subjects.
  • Filtering out chores you have already done.

👩‍🏫 Teacher Notes

  • Focus on reading M code first, then writing simple modifications.
  • Use the Advanced Editor to show students the code behind their clicks.
  • Encourage students to change values and see what happens.

👨‍👩‍👧 Parent Tips

  • Help your child understand variables by comparing them to containers.
  • Show them how to add comments to remember what each step does.
  • Practice together by writing simple formulas in Excel and then viewing the M code.

💡 Interesting Facts

  • M stands for “Mashup” – because it mashes data together!
  • M is a functional language, meaning it focuses on transforming data.
  • Power Query writes M code behind every single click you make.

🤔 Did You Know?

  • You can copy M code from one query and paste it into another to reuse your work.
  • M is used in Power BI, Excel, and even in some cloud services.

🧷 Remember This

  • M code is case‑sensitive – pay attention to capital letters.
  • Every step in M creates a new table; old tables stay unchanged.
  • Use comments (//) to explain your code.
  • The Advanced Editor is your friend – don’t be scared to explore it.

⚠️ Common Mistakes

  • Forgetting to change the “in” line to the correct step name.
  • Using wrong column names (check spelling!).
  • Mixing text and numbers without converting types.
  • Forgetting commas between steps in the “let” block.

✅ Best Practices

  • Always give your steps meaningful names (e.g., “FilteredData”, not “Step3”).
  • Add comments to explain complex steps.
  • Test small pieces of code before combining them.
  • Keep your code tidy – use indentation and spaces.

🖼️ Illustrations

M Code Structure (let … in)
+-----------------------------------+
| let                               |
|   Step1 = ...                     |
|   Step2 = ...                     |
|   Step3 = ...                     |
| in                                |
|   Step3   (this is the output)    |
+-----------------------------------+
Data Flow in M
+----------+    +----------+    +----------+
| Source   | -> | Cleaned  | -> | Result   |
| (raw)    |    | (fixed)  |    | (final)  |
+----------+    +----------+    +----------+

📊 Comparison Tables

Button ActionM Code Equivalent
Remove Blank RowsTable.SelectRows(Source, each Record.FieldCount(_) > 0)
Split Column by SpaceTable.SplitColumn(Source, "FullName", Splitter.SplitTextByDelimiter(" "))
Change Data Type to NumberTable.TransformColumnTypes(Source, {{"Column", type number}})
Add Custom ColumnTable.AddColumn(Source, "New", each [A] + [B])

📌 End‑of‑Module Summary

Congratulations! You have taken your first steps into the world of M language. You learned that M is the recipe behind Power Query. You can now read and write simple M expressions, use variables, add comments, and apply common functions like Table.AddColumn, Table.SelectRows, and Table.TransformColumnTypes. You also learned about the let…in structure, the power of “each” and “_”, and how to create your own functions. Remember, M gives you superpowers – the more you practice, the more data magic you can perform!

❓ Frequently Asked Questions

  1. What does M stand for? – M stands for Mashup.
  2. Where do I write M code? – In the Advanced Editor.
  3. What is the difference between let and in? – let defines steps, in returns the final result.
  4. What is a variable in M? – A name given to a value or a step.
  5. How do I add a comment? – Use // or /* ... */.
  6. What does “each” do? – It applies a function to every row.
  7. What is “_” used for? – It represents the current row.
  8. Can I reuse M code? – Yes, you can copy and paste or create functions.
  9. What is a function in M? – A reusable block of code.
  10. Is M case‑sensitive? – Yes, so “Name” and “name” are different.

📝 Review Questions

  1. What is M language used for?
  2. Where can you see the M code behind your steps?
  3. What is the structure that holds steps in M?
  4. How do you write a variable in M?
  5. What is a comment and why use it?
  6. Name two M functions.
  7. What does Table.AddColumn do?
  8. What does Table.SelectRows do?
  9. What is the “each” keyword used for?
  10. How do you combine two tables in M?
  11. What is a record in M?
  12. What is a list in M?
  13. Why is error handling important?
  14. What does the “in” keyword do?
  15. Can you reuse M code? If yes, how?

✍️ Fill‑in‑the‑Blank

  1. M stands for _______.
  2. You write M code in the _______ Editor.
  3. The _______ structure holds steps and returns a result.
  4. A _______ is a name given to a value or step.
  5. _______ are notes that do not affect the code.

✅ True or False

  1. M is case‑sensitive. (True)
  2. You cannot see M code in Power Query. (False)
  3. “let” is used to define steps. (True)
  4. Table.AddColumn removes columns. (False – it adds columns)
  5. “each” applies to every row. (True)

🔘 Multiple Choice Questions

  1. What language does Power Query use?
    a) Python b) M c) SQL d) Java
    Answer: b
  2. Where do you edit M code?
    a) Formula Bar b) Advanced Editor c) Query Settings d) Data View
    Answer: b
  3. Which keyword starts the step list?
    a) in b) let c) begin d) start
    Answer: b
  4. What does “//” do?
    a) Adds a comment b) Adds a number c) Removes a column d) Filters rows
    Answer: a
  5. Which function creates a new column?
    a) Table.AddColumn b) Table.RemoveColumns c) Table.SelectRows d) Table.Combine
    Answer: a
  6. Which function filters rows?
    a) Table.SelectRows b) Table.AddColumn c) Table.TransformColumnTypes d) Table.Combine
    Answer: a
  7. What does “each” refer to?
    a) Every row b) The first row c) The last row d) No row
    Answer: a
  8. Which symbol represents the current row?
    a) $ b) # c) _ d) @
    Answer: c
  9. What is a variable in M?
    a) A step name b) A function c) A comment d) A table
    Answer: a
  10. Which function changes data types?
    a) Table.TransformColumnTypes b) Table.AddColumn c) Table.RemoveColumns d) Table.Combine
    Answer: a
  11. What does Table.Combine do?
    a) Stacks tables vertically b) Joins tables horizontally c) Removes columns d) Filters rows
    Answer: a
  12. Which is the correct way to write a record?
    a) {1,2,3} b) [Name="Ade"] c) (1,2,3) d) <1,2,3>
    Answer: b
  13. What is a list in M?
    a) A collection of values b) A single value c) A table d) A function
    Answer: a
  14. Can you reuse M code?
    a) Yes, by copying or using functions b) No, never c) Only once d) Only in Excel
    Answer: a
  15. What is error handling?
    a) Preventing code from breaking b) Creating errors c) Ignoring errors d) Deleting errors
    Answer: a

🔗 Matching Exercises

Match the M keyword/function with its description:

Keyword/FunctionDescription
1. letA. Defines steps
2. inB. Returns the result
3. eachC. Applies to every row
4. Table.AddColumnD. Adds a new column

Answers: 1-A, 2-B, 3-C, 4-D

✏️ Short Answer Questions

  1. Explain the let…in structure in your own words.
  2. What is the difference between a variable and a function?
  3. Why is it useful to add comments to your code?
  4. Give an example of when you would use Table.SelectRows.
  5. How would you create a custom column that doubles the price?

📖 Scenario‑based Exercises

Scenario 1: You have a table with Product, Price, and Quantity. Write M code to add a Total column (Price * Quantity).

Scenario 2: You have a list of students with scores. Write M code to keep only students who scored 80 or above.

👥 Group Activity

In groups, take a messy dataset and write M code to clean it. Each group presents their code and explains what each step does. Compare different approaches.

🧑‍🎓 Individual Activity

Open the Advanced Editor in Power Query and find the code generated by your last cleaning task. Add a comment to each step explaining what it does. Then, add a new step that filters the data further.

🗣️ Classroom Discussion Questions

  1. Why is M considered a “functional” language?
  2. What are the advantages of writing code instead of using buttons?
  3. How can functions help you save time?

🛠️ Mini Project

Create a Power Query that cleans a sample dataset using only M code. Include at least 5 steps (e.g., remove blanks, change types, add custom column, filter, and remove a column). Write your code in the Advanced Editor and test it.

💻 Practical Assignment

Take the dataset from the previous module’s practical assignment. Instead of using buttons, write M code to perform the same cleaning steps. Submit the M code and a short report comparing the button approach vs. the code approach.

🏆 Challenge Exercise

Write an M function that takes a table and a column name, and returns the table sorted by that column in descending order. Test it on a sample table. Hint: use Table.Sort.

🔍 Quiz Answers

Fill‑in‑the‑Blank: 1. Mashup 2. Advanced 3. let…in 4. variable 5. Comments

True or False: 1-T, 2-F, 3-T, 4-F, 5-T

Multiple Choice: 1-b, 2-b, 3-b, 4-a, 5-a, 6-a, 7-a, 8-c, 9-a, 10-a, 11-a, 12-b, 13-a, 14-a, 15-a

🎁 Key Takeaways

  • M language gives you full control over your data transformations.
  • Every click in Power Query translates to M code.
  • You can read, write, and edit M code in the Advanced Editor.
  • Variables, functions, and comments make your code clear and reusable.
  • Practice writing M code – it will make you a true data expert.

🔜 Preparation for Module Six

In Module Six, we will dive into “Advanced M – Working with Lists, Records, and Custom Functions”. You will learn how to loop through data, handle errors like a pro, and build complex transformations. Get ready to become a master of M!

Note: This is Module Five. Module Four covered cleaning and shaping. We now move to Module Six, where we will explore advanced M concepts. Keep practicing – you are doing great!

7

Module Six

Module 6 · Certified Power Query for Data Analysis Expert

📘 Module Six: Advanced M – Lists, Records, and Custom Functions

Welcome, young data champion! In Module Five, we learned the basics of M language – variables, steps, and simple functions. Now it is time to level up. In this module, we will explore lists (like bags of items), records (like cards with details), and custom functions (like recipes you invent yourself). You will learn how to loop through data, transform lists, and build your own powerful tools. By the end, you will be able to write M code that can handle almost any data challenge!

🎯 Learning Objectives

  • Understand lists and how to work with them in M.
  • Understand records and how to access their fields.
  • Create and use custom functions that accept parameters.
  • Use List.Transform to apply a function to every item in a list.
  • Use Record.Combine and Record.Field to work with records.
  • Combine lists and records with tables.
  • Handle errors gracefully using try and otherwise.
  • Write reusable M code that saves time.

📖 Warm‑up Story: The Magic Toolbox

Fatima loves fixing things. Her grandfather gives her a toolbox with many compartments. One compartment holds screws (like a list of values). Another holds instruction cards (like records with details). She also has a special tool that can turn any screw and any card into a new creation – that’s like a custom function!
In this module, you will build your own toolbox. You will learn to store data in lists, organize it in records, and create functions that can work on any data you give them. Let’s start building!

📚 Main Lessons

Lesson 1: What is a List in M?

Definition: A list is a collection of values enclosed in curly braces { }.

Why important: Lists let you store many items together and work with them all at once.

Simple explanation: Like a bag of marbles – you can count them, add more, or take some out.

Real‑life example: A shopping list: {"milk", "bread", "eggs"}.

School example: A list of test scores: {80, 90, 70}.

Home example: A list of chores: {"sweep", "wash", "cook"}.

Nigerian example: A list of states: {"Lagos", "Abuja", "Kano"}.

let
    MyList = {10, 20, 30, 40}
in
    MyList

Mini summary: A list is a collection of items inside { }.

Lesson 2: Accessing Items in a List

Definition: You can get an item from a list using its position (index), starting from 0.

Why important: You often need to pick one specific item from a list.

Simple explanation: Like picking the third marble from your bag.

Real‑life example: The first item on a list is position 0.

School example: In a list of scores, {80,90,70}, the second score is at index 1 (90).

Home example: Your chore list – index 0 is “sweep”.

Nigerian example: List of states – index 0 is “Lagos”.

let
    MyList = {10, 20, 30},
    FirstItem = MyList{0}   // 10
in
    FirstItem

Mini summary: Use {index} to pick an item from a list.

Lesson 3: List.Transform – Changing Every Item

Definition: List.Transform applies a function to each item in a list and returns a new list.

Why important: It lets you change all items at once – like doubling every number.

Simple explanation: Like giving every marble a coat of paint – all at once.

Real‑life example: Convert all prices from naira to dollars.

School example: Add 5 marks to every score.

Home example: Double the quantity of each item in a recipe.

Nigerian example: Add VAT (7.5%) to every price.

let
    MyList = {10, 20, 30},
    NewList = List.Transform(MyList, each _ * 2)   // {20, 40, 60}
in
    NewList

Mini summary: List.Transform changes every item in a list.

Lesson 4: What is a Record in M?

Definition: A record is a set of fields with names and values, like a row in a table.

Why important: Records organize data with labels, so you know what each value means.

Simple explanation: Like a student ID card – it has Name, Age, and Class.

Real‑life example: A product record: [Product="Milk", Price=200].

School example: A student record: [Name="Ade", Score=80].

Home example: A chore record: [Chore="Sweep", Time="10am"].

Nigerian example: A state record: [State="Lagos", Population=20M].

let
    MyRecord = [Name="Ade", Age=10, Class="P5"]
in
    MyRecord

Mini summary: A record is a labelled collection of values inside [ ].

Lesson 5: Accessing Fields in a Record

Definition: You can get a field’s value using the dot notation or Record.Field.

Why important: You need to extract specific information from a record.

Simple explanation: Like looking at the “Name” on an ID card.

Real‑life example: Get the price from a product record.

School example: Get the score from a student record.

Home example: Get the time from a chore record.

Nigerian example: Get the population from a state record.

let
    MyRecord = [Name="Ade", Score=80],
    StudentName = MyRecord[Name]   // or MyRecord.Name
in
    StudentName

Mini summary: Use [FieldName] to get a value from a record.

Lesson 6: Combining Records – Record.Combine

Definition: Record.Combine merges two or more records into one.

Why important: You may have information in separate records that you want to bring together.

Simple explanation: Like sticking two cards together to make a bigger card.

Real‑life example: Combine product details and price records.

School example: Combine student name and marks records.

Home example: Combine chore name and time records.

Nigerian example: Combine state name and capital records.

let
    Rec1 = [Name="Ade", Age=10],
    Rec2 = [Score=80, Class="P5"],
    Combined = Record.Combine({Rec1, Rec2})
in
    Combined   // [Name="Ade", Age=10, Score=80, Class="P5"]

Mini summary: Record.Combine merges records.

Lesson 7: Lists of Records – Tables in Disguise

Definition: A list of records is like a table – each record is a row.

Why important: Many data sources give you a list of records.

Simple explanation: Like a class register – each row is a student record.

Real‑life example: A list of products, each with Name and Price.

School example: A list of students, each with Name and Score.

Home example: A list of chores, each with Chore and Time.

Nigerian example: A list of states, each with State and Capital.

let
    MyTable = {
        [Name="Ade", Score=80],
        [Name="Bola", Score=90],
        [Name="Chidi", Score=70]
    }
in
    MyTable

Mini summary: A list of records is a great way to store tabular data.

Lesson 8: Transforming a List of Records

Definition: You can use List.Transform on a list of records to change or extract fields.

Why important: It lets you manipulate each row of your data.

Simple explanation: Like going through each student and adding 5 marks.

School example: Add 10 to every score in a list.

Home example: Add a “Done” field to every chore.

Nigerian example: Add a “Region” field to every state record.

let
    Data = {
        [Name="Ade", Score=80],
        [Name="Bola", Score=90]
    },
    Updated = List.Transform(Data, each _ & [Score = [Score] + 5])
in
    Updated   // scores become 85 and 95

Mini summary: You can transform lists of records row by row.

Lesson 9: Custom Functions – Your Own Recipes

Definition: A custom function is a block of code you write to perform a specific task.

Why important: You can reuse the same code many times with different inputs.

Simple explanation: Like a recipe for “fried rice” – you can make it whenever you want.

Real‑life example: A function to calculate discount.

School example: A function to calculate average.

Home example: A function to convert currency.

Nigerian example: A function to add VAT.

let
    AddTen = (x) => x + 10,
    Result = AddTen(5)   // 15
in
    Result

Mini summary: Functions are reusable recipes in M.

Lesson 10: Functions with Multiple Parameters

Definition: A function can take more than one input, like (x, y) => x + y.

Why important: Many tasks need more than one piece of information.

Simple explanation: Like adding two numbers – you need both numbers.

School example: A function to calculate total (maths + english).

Home example: A function to calculate total cost (price * quantity).

Nigerian example: A function to calculate total with VAT.

let
    Add = (x, y) => x + y,
    Sum = Add(5, 3)   // 8
in
    Sum

Mini summary: Functions can have many inputs.

Lesson 11: Using Functions with Lists – List.Transform and Custom Functions

Definition: You can pass a custom function to List.Transform to apply it to every item.

Why important: It gives you complete flexibility.

Simple explanation: Like having a special machine that can do any job you tell it.

School example: Apply a “pass/fail” function to every score.

Home example: Apply a “discount” function to every price.

Nigerian example: Apply a “region” function to every state.

let
    AddTen = (x) => x + 10,
    MyList = {10, 20, 30},
    NewList = List.Transform(MyList, AddTen)   // {20, 30, 40}
in
    NewList

Mini summary: Custom functions make List.Transform very powerful.

Lesson 12: Error Handling with try and otherwise

Definition: “try” attempts a step; if it fails, “otherwise” gives a fallback value.

Why important: It prevents your code from crashing when something goes wrong.

Simple explanation: Like wearing a helmet – if you fall, it protects you.

School example: If a score is missing, use 0.

Home example: If an item has no price, set it to 100.

Nigerian example: If a state population is missing, use “Unknown”.

let
    SafeDivide = (a, b) => try a / b otherwise 0,
    Result = SafeDivide(10, 0)   // 0 (no error)
in
    Result

Mini summary: try…otherwise keeps your code safe from errors.

Lesson 13: Building a Complete Custom Function

Definition: A full function can have multiple steps inside using let…in.

Why important: Complex tasks need multiple steps.

Simple explanation: Like a recipe with many steps – mix, knead, bake.

School example: A function to calculate grade (A, B, C) from score.

Home example: A function to calculate total with tax and discount.

Nigerian example: A function to clean a name (capitalize, remove spaces).

let
    Grade = (score) =>
        let
            GradeText = if score >= 70 then "A" else "B"
        in
            GradeText,
    Result = Grade(85)   // "A"
in
    Result

Mini summary: Functions can have multiple steps inside.

Lesson 14: Using Record.Field and Record.HasField

Definition: Record.Field gets a field value; Record.HasField checks if a field exists.

Why important: Sometimes you don’t know if a field is present.

Simple explanation: Like checking if a student has a “Score” field before using it.

School example: Only add marks if the “Score” field exists.

Home example: Only add a price if the “Price” field exists.

Nigerian example: Only add a capital if the “Capital” field exists.

let
    MyRecord = [Name="Ade"],
    HasScore = Record.HasField(MyRecord, "Score")   // false
in
    HasScore

Mini summary: Record.Field and HasField help you work safely with records.

Lesson 15: Recursion – Functions Calling Themselves

Definition: Recursion is when a function calls itself to solve a problem.

Why important: It is useful for repetitive tasks like summing a list.

Simple explanation: Like counting marbles one by one until you reach the end.

School example: Sum all numbers in a list.

Home example: Count all items in a shopping list.

Nigerian example: Count all states in a list.

let
    SumList = (lst) =>
        if List.Count(lst) = 0 then 0
        else List.First(lst) + SumList(List.Skip(lst, 1)),
    Result = SumList({10, 20, 30})   // 60
in
    Result

Mini summary: Recursion is a function that calls itself – powerful but advanced.

🔑 Key Vocabulary (simple definitions)

  • List: A collection of values in { }.
  • Record: A set of labelled values in [ ].
  • Index: The position of an item in a list (starting from 0).
  • List.Transform: A function that changes every item in a list.
  • Record.Combine: Merges two records.
  • Custom function: A reusable block of code.
  • Parameter: An input to a function.
  • try … otherwise: Error handling that prevents crashes.
  • Recursion: A function that calls itself.
  • Field: A named part of a record.

🧠 Important Concepts

  • Immutability: Lists and records are not changed; new ones are created.
  • Function composition: You can pass functions to other functions.
  • Scope: Variables inside a function are not visible outside.
  • Lazy evaluation: M only computes values when needed.

📝 Step‑by‑Step Explanations

How to create a custom function that cleans a name

  1. Write: CleanName = (fullName) => Text.Proper(Text.Trim(fullName))
  2. Test it: CleanName(" ade ojo ") returns “Ade Ojo”.
  3. Use it in List.Transform to clean many names.

How to safely access a record field

  1. Use Record.HasField(record, "FieldName") to check.
  2. If true, use Record.Field(record, "FieldName").
  3. If false, provide a default value.

🌍 Real‑life Examples

  • E-commerce: Use List.Transform to calculate discounts on a list of products.
  • Healthcare: Use records to store patient data and functions to calculate BMI.
  • Finance: Use custom functions to calculate interest rates.

🇳🇬 Nigerian Examples

  • Nigerian Stock Exchange: Use lists to track share prices and functions to calculate returns.
  • Population data: Use records for each state and functions to compute density.
  • School system: Use List.Transform to add scores for all students.

🧸 Fun Examples

  • A list of your favourite games – transform to add “(fun)” to each.
  • A record for your pet – get its age field.
  • A custom function that doubles your allowance – use it every week.

🏠 Everyday Examples

  • List of homework tasks – transform to add “due date”.
  • Record of a recipe – get cooking time field.
  • Custom function to convert miles to kilometres.

👩‍🏫 Teacher Notes

  • Emphasize the difference between lists (ordered) and records (labelled).
  • Use real data to demonstrate List.Transform and Record.Combine.
  • Encourage students to write simple functions and test them.

👨‍👩‍👧 Parent Tips

  • Help your child create a list of family members and transform it.
  • Show them how to make a record for each family member.
  • Practice writing simple functions together.

💡 Interesting Facts

  • Lists in M can hold any type of value – numbers, text, even other lists!
  • Records are used extensively in Power Query to pass parameters.
  • Many built‑in Power Query functions are written in M.

🤔 Did You Know?

  • You can convert a list of records directly to a table using Table.FromRecords.
  • M supports infinite lists using functions like List.Generate.

🧷 Remember This

  • Lists are for collections; records are for labelled data.
  • Use List.Transform to change all items in a list.
  • Custom functions make your code reusable and clean.
  • Always handle errors with try…otherwise.

⚠️ Common Mistakes

  • Using { } for records and [ ] for lists – they are opposite!
  • Forgetting that list indices start at 0.
  • Not checking if a field exists before accessing it.
  • Writing functions that are too complex – break them down.

✅ Best Practices

  • Always give your lists and records meaningful names.
  • Write small, focused functions that do one thing well.
  • Use comments to explain complex logic.
  • Test your functions with simple inputs first.

🖼️ Illustrations

List as a Bag of Marbles
+-----+-----+-----+-----+
| 10  | 20  | 30  | 40  |
+-----+-----+-----+-----+
Index: 0    1    2    3
Record as an ID Card
+------------------+
| Name: Ade        |
| Age:  10         |
| Class: P5        |
+------------------+
List of Records (Table)
+----------+----------+----------+
| Name     | Score    | Grade    |
+----------+----------+----------+
| Ade      | 80       | A        |
+----------+----------+----------+
| Bola     | 90       | A        |
+----------+----------+----------+

📊 Comparison Tables

ConceptSyntaxUse
List{1,2,3}Collection of values
Record[Name="Ade"]Labelled values
List.TransformList.Transform(list, each _ * 2)Change every item
Record.CombineRecord.Combine({rec1, rec2})Merge records

📌 End‑of‑Module Summary

You have now mastered lists, records, and custom functions in M! You can create lists of any type, access items by index, and transform entire lists with List.Transform. You know how to build records, combine them, and work with lists of records. You have written your own functions with parameters and even used error handling to make your code safe. You are now equipped to write powerful, reusable M code that can handle complex data challenges. Well done!

❓ Frequently Asked Questions

  1. What is the difference between a list and a record? – A list is a collection of values; a record has labelled fields.
  2. How do I access the first item in a list? – Use MyList{0}.
  3. How do I merge two records? – Use Record.Combine({rec1, rec2}).
  4. What does List.Transform do? – It applies a function to every item and returns a new list.
  5. How do I write a custom function? – Use (parameters) => expression or let…in.
  6. What is try … otherwise? – It attempts an operation and gives a default if it fails.
  7. Can a function have multiple steps? – Yes, use let…in inside the function.
  8. What is recursion? – A function that calls itself.
  9. How do I check if a field exists in a record? – Use Record.HasField.
  10. Can I convert a list of records to a table? – Yes, use Table.FromRecords.

📝 Review Questions

  1. What is a list in M?
  2. How do you access the third item in a list?
  3. What does List.Transform do?
  4. What is a record?
  5. How do you get a field from a record?
  6. What is Record.Combine used for?
  7. How do you create a custom function?
  8. What is the purpose of try … otherwise?
  9. What is a parameter in a function?
  10. How do you apply a custom function to every item in a list?
  11. What is recursion?
  12. How do you check if a field exists in a record?
  13. What does Table.FromRecords do?
  14. Give an example of a list of records.
  15. Why is error handling important?

✍️ Fill‑in‑the‑Blank

  1. A list is enclosed in _______ braces.
  2. A record is enclosed in _______ brackets.
  3. List.Transform applies a function to every _______ in a list.
  4. _______ combines two or more records.
  5. A _______ is a block of code that you can reuse.

✅ True or False

  1. List indices start at 1. (False – start at 0)
  2. A record can have only one field. (False – can have many)
  3. List.Transform changes the original list. (False – it creates a new list)
  4. try … otherwise prevents errors. (True)
  5. Recursion is a function that calls itself. (True)

🔘 Multiple Choice Questions

  1. Which syntax creates a list?
    a) [1,2,3] b) {1,2,3} c) (1,2,3) d) <1,2,3>
    Answer: b
  2. Which syntax creates a record?
    a) [Name="Ade"] b) {Name="Ade"} c) (Name="Ade") d)
    Answer: a
  3. How do you get the second item of a list MyList?
    a) MyList{1} b) MyList[1] c) MyList(1) d) MyList.1
    Answer: a
  4. What does List.Transform do?
    a) Transforms a record b) Transforms a list c) Combines lists d) Filters a list
    Answer: b
  5. Which function merges records?
    a) List.Combine b) Record.Combine c) Table.Combine d) Combine.Records
    Answer: b
  6. What is the correct way to write a function that doubles a number?
    a) (x) => x * 2 b) x => x * 2 c) (x) => x + 2 d) x => x + 2
    Answer: a
  7. What does try … otherwise do?
    a) Tries a step, otherwise gives a default b) Tries a step, otherwise stops c) Combines steps d) Deletes steps
    Answer: a
  8. What is recursion?
    a) A function that calls itself b) A function that calls another c) A list of functions d) A record of functions
    Answer: a
  9. How do you check if a record has a field?
    a) Record.HasField b) Record.FieldExists c) Record.Contains d) Record.Has
    Answer: a
  10. Which function converts a list of records to a table?
    a) Table.FromRecords b) Table.FromList c) Table.Convert d) Table.Records
    Answer: a
  11. What is an index?
    a) The position of an item in a list b) A type of record c) A function d) An error
    Answer: a
  12. Can a list hold different data types?
    a) Yes b) No c) Only numbers d) Only text
    Answer: a
  13. What is the purpose of a custom function?
    a) Reuse code b) Create errors c) Delete data d) Format text
    Answer: a
  14. What does List.Transform return?
    a) A new list b) The original list c) A record d) A table
    Answer: a
  15. Which is a best practice?
    a) Use meaningful names b) Use short names c) No comments d) No functions
    Answer: a

🔗 Matching Exercises

Match the M concept with its description:

ConceptDescription
1. ListA. A collection of values in { }
2. RecordB. A set of labelled fields in [ ]
3. List.TransformC. Applies a function to every item
4. try … otherwiseD. Error handling

Answers: 1-A, 2-B, 3-C, 4-D

✏️ Short Answer Questions

  1. Explain the difference between a list and a record.
  2. Write an M expression to create a list of numbers from 1 to 5.
  3. How do you apply a function that adds 10 to every number in a list?
  4. Write a custom function that takes a score and returns “Pass” if score ≥ 50.
  5. Why would you use try … otherwise?

📖 Scenario‑based Exercises

Scenario 1: You have a list of product records: [Product="Rice", Price=1000], etc. Write M code to add a 10% tax to each product’s price.

Scenario 2: You have a record with Name, Age, and Score. Write a function that returns the grade based on the score.

👥 Group Activity

Each group creates a list of 10 records (e.g., students with Name, Score). Then, using List.Transform and a custom function, they transform the list to add a “Grade” column. Groups compare their approaches.

🧑‍🎓 Individual Activity

Write a custom function that cleans a list of names (capitalizes each, removes extra spaces). Test it on a list of your friends’ names.

🗣️ Classroom Discussion Questions

  1. When would you use a list instead of a record?
  2. Why is immutability important in M?
  3. How can custom functions save you time?

🛠️ Mini Project

Build a Power Query that takes a list of state records (Name, Capital, Population). Use a custom function to add a “Region” column (e.g., South, North) based on the state. Output the transformed list.

💻 Practical Assignment

Using a sample dataset of employees (Name, Department, Salary), write M code to: (1) Create a list of records, (2) Add a “Bonus” column (10% of salary), (3) Filter to only employees with salary > 50000. Submit your M code.

🏆 Challenge Exercise

Write a recursive function that sums all numbers in a list without using List.Sum. Test it with a list of 10 numbers.

🔍 Quiz Answers

Fill‑in‑the‑Blank: 1. curly 2. square 3. item 4. Record.Combine 5. function

True or False: 1-F, 2-F, 3-F, 4-T, 5-T

Multiple Choice: 1-b, 2-a, 3-a, 4-b, 5-b, 6-a, 7-a, 8-a, 9-a, 10-a, 11-a, 12-a, 13-a, 14-a, 15-a

🎁 Key Takeaways

  • Lists store ordered collections; records store labelled data.
  • List.Transform is a powerful way to change all items in a list.
  • Custom functions let you reuse code and keep your work clean.
  • Error handling with try…otherwise makes your code robust.
  • Practice with lists, records, and functions – they are the building blocks of M.

🔜 Preparation for Module Seven

In Module Seven, we will dive into “Performance and Efficiency in Power Query”. You will learn how to make your queries run faster, reduce memory usage, and handle big data like a pro. Get ready to optimize your data magic!

Note: This is Module Six. Module Five covered basic M. We now move to Module Seven, where we will focus on making our queries efficient and fast. Keep coding – you are becoming a true M master!

8

Module Seven

Module 7 · Power Query for Data Analysis Expert

🧹 Module Seven: Cleaning Data Like a Pro

Welcome, young data explorer! In this module, we will learn how to make our data sparkly clean. Imagine you have a big bowl of fruits. Some fruits are rotten, some have dirt, and some are not even fruits! You wouldn't want to eat that, right? In the same way, when we work with data, we must clean it before we use it. Cleaning data means fixing mistakes, removing things we don't need, and making everything neat and tidy. This is a very important job for a data analyst. After this lesson, you will be a Data Cleaning Champion!

🎯 Learning Objectives

  • Understand what data cleaning is and why it matters.
  • Learn how to remove duplicate rows in Power Query.
  • Learn how to fix missing values (blanks).
  • Learn how to split columns into smaller pieces.
  • Learn how to change data types (text, number, date).
  • Learn how to rename columns and headers.
  • Learn how to trim extra spaces from text.
  • Learn how to replace values (change "N/A" to "Not Available").
  • Use the "Remove Rows" and "Keep Rows" tools.
  • Understand how to use the "Fill Down" feature.
  • Combine cleaning steps to make a perfect table.

📖 Warm-up Story: The Messy Market List

Chidi loves helping his mum at the market. One day, his mum gave him a messy list written on a crumpled paper. The list had things like:

milk, MILK, 2 milk, eggs, egg, 5 eggs, bread, bred, butter, buter, jam

Chidi was confused! Some items were repeated, some were spelled wrong, and some had numbers mixed in. He decided to clean the list. He crossed out the repeated "milk", fixed "bred" to "bread", and wrote "butter" correctly. Then he grouped all the eggs together. After cleaning, the list was perfect, and his mum was very happy. That is exactly what we do with data in Power Query – we clean it so that it makes sense!

📚 Main Lessons (15 Lessons)

Lesson 1: What is Data Cleaning?

Definition: Data cleaning is the process of finding and fixing errors in data.

Why important: Dirty data gives wrong answers. Clean data gives correct answers.

Simple explanation: It's like washing your hands before eating. You remove germs (errors) so you don't get sick (wrong results).

Real-life example: A teacher has a list of students. Some names are spelled wrong. She corrects them. That's cleaning.

School example: Your class register has duplicate names. You remove them.

Home example: You have a list of chores. Some chores are written twice. You delete the extras.

Nigerian example: A shopkeeper in Lagos records sales. Some entries say "N500" and others say "500 Naira". He makes them all "500 Naira".

Illustration:

  Dirty Data          ➡️   Clean Data
  -----------------        -----------------
  Name:   Tunde           Name:   Tunde
  Age:    25              Age:    25
  City:   Lagos           City:   Lagos
  Name:   Tunde   (dup)   (removed)

Mini summary: Data cleaning fixes mistakes so our data is accurate and useful.

Lesson 2: Removing Duplicate Rows

Definition: Duplicate rows are rows that are exactly the same as another row.

Why important: Duplicates make counts wrong (e.g., counting the same person twice).

Simple explanation: Imagine you have a list of your friends. If "Ade" appears twice, you might think you have two friends named Ade. But it's the same person. So we remove one.

Real-life example: A company sends newsletters. If email addresses are duplicated, people get two emails. They get annoyed.

School example: Your teacher has a list of students who brought books. If a student is listed twice, the count is wrong.

Home example: Your family grocery list has "rice" written three times. You keep only one.

Nigerian example: A bank in Abuja records transactions. The same transaction might be entered twice by mistake. Removing duplicates fixes the balance.

How to do it in Power Query: Select your table, go to the "Home" tab, click "Remove Rows", then "Remove Duplicates".

Illustration:

Before:                   After:
+----+-------+           +----+-------+
| ID | Name  |           | ID | Name  |
+----+-------+           +----+-------+
| 1  | Bola  |           | 1  | Bola  |
| 2  | Tayo  |           | 2  | Tayo  |
| 1  | Bola  |  ← dup   | 3  | Zain  |
| 3  | Zain  |           +----+-------+
+----+-------+

Mini summary: Use "Remove Duplicates" to delete rows that are identical.

Lesson 3: Fixing Missing Values (Blanks)

Definition: Missing values are empty cells in your data.

Why important: Blanks can cause errors in calculations (e.g., sum of blank is zero, but maybe you wanted to ignore it).

Simple explanation: If a form asks for your age and you leave it blank, the computer doesn't know your age. We can fill it with something like "Unknown" or the average age.

Real-life example: A survey has some questions unanswered. We can fill them with "No answer".

School example: A test score list has a blank for a student who was absent. We can write "Absent".

Home example: A list of birthdays has a missing date. We can write "Not known".

Nigerian example: A hospital in Kano has patient records. Some have no phone number. They fill with "0000".

How to do it: In Power Query, use "Replace Values" to replace null or blank with something else. Or use "Fill Down" to copy the value from above.

Illustration:

Before:           After (Fill Down):
+----+-------+    +----+-------+
| Day| Temp  |    | Day| Temp  |
+----+-------+    +----+-------+
| Mon| 30°   |    | Mon| 30°   |
| Tue|       |    | Tue| 30°   |  ← copied from Mon
| Wed| 28°   |    | Wed| 28°   |
+----+-------+    +----+-------+

Mini summary: Fill blanks with a value or copy from above to avoid empty cells.

Lesson 4: Splitting Columns

Definition: Splitting means dividing one column into two or more columns.

Why important: Sometimes one column has too much information (e.g., "First Name Last Name"). We split it to separate first and last names.

Simple explanation: If you have a jar of mixed sweets, you separate the red ones from the green ones. That's splitting.

Real-life example: A column has "City, State". We split into "City" and "State".

School example: A column has "Subject-Grade" like "Math-A". Split into "Subject" and "Grade".

Home example: A list of "Item-Qty" like "Apples-5". Split into "Item" and "Qty".

Nigerian example: A column has "LGA, State" like "Ikeja, Lagos". Split into "LGA" and "State".

How to do it: Select the column, go to "Transform" tab, click "Split Column", choose "By Delimiter" (like a comma or space).

Illustration:

Before:              After:
+----------------+   +---------+---------+
| Full Name      |   | First   | Last    |
+----------------+   +---------+---------+
| Chidi Okonkwo  |   | Chidi   | Okonkwo |
| Amina Bello    |   | Amina   | Bello   |
+----------------+   +---------+---------+

Mini summary: Split columns to separate data that is combined.

Lesson 5: Changing Data Types

Definition: Data type tells Power Query what kind of data is in a column (text, number, date, etc.).

Why important: If you have numbers stored as text, you cannot add them. So you must change to number type.

Simple explanation: It's like sorting toys: cars go in the car box, dolls in the doll box. You put each data in its correct box.

Real-life example: A column has "1000" but it is text. You change it to number so you can sum it.

School example: "Age" column has numbers but is stored as text. You change to number to calculate average age.

Home example: "Price" column has "₦500" but with a symbol. You remove the symbol and change to number.

Nigerian example: "Date of Birth" is stored as text "12-05-2010". Change to Date type to calculate age.

How to do it: Click the little icon next to the column header (like "ABC" or "123") and choose the correct type (Text, Whole Number, Decimal, Date).

Illustration:

Before (Text)      After (Number)
+-------+          +-------+
| Price |          | Price |
+-------+          +-------+
| 500   |          |  500  |
| 1000  |          | 1000  |
+-------+          +-------+
(Can't sum)        (Can sum = 1500)

Mini summary: Always set the right data type so Power Query can work properly.

Lesson 6: Renaming Columns

Definition: Renaming means changing the name of a column.

Why important: Sometimes column names are not clear (e.g., "Col1"). We rename to something meaningful like "Student Name".

Simple explanation: It's like putting a label on a box so you know what's inside.

Real-life example: A column named "B" actually contains "Age". Rename it to "Age".

School example: "X" column is "Score". Rename to "Math Score".

Home example: "Item" column is actually "Fruit". Rename to "Fruit".

Nigerian example: "Column1" is "State". Rename to "State of Origin".

How to do it: Double-click the column header and type the new name. Or right-click and choose "Rename".

Illustration:

Before:   After:
+------+  +---------+
| Col1 |  | Student |
+------+  +---------+
| Ade  |  | Ade     |
+------+  +---------+

Mini summary: Give columns clear, descriptive names.

Lesson 7: Trimming Extra Spaces

Definition: Trimming removes unwanted spaces at the beginning or end of text.

Why important: " Bola " is not the same as "Bola". Extra spaces can cause problems when you compare or group.

Simple explanation: Imagine writing your name with a big space before it. That looks messy. We erase the space.

Real-life example: A list of cities has " Lagos" and "Lagos". They should be the same. Trim them.

School example: " John " and "John" are different to a computer. Trim to make them match.

Home example: " rice " and "rice" should be the same when searching.

Nigerian example: " Abuja" and "Abuja " are both Abuja after trimming.

How to do it: Select the column, go to "Transform" tab, click "Format", then "Trim".

Illustration:

Before:     After:
"  Bola  "  "Bola"
"Tunde "    "Tunde"
" Amina"    "Amina"

Mini summary: Trim to remove extra spaces and make text clean.

Lesson 8: Replacing Values

Definition: Replacing means changing one value to another (e.g., change "N/A" to "Not Available").

Why important: Standardizes data. For example, "Yes", "Y", "y" all mean the same. We replace them all with "Yes".

Simple explanation: If you have different names for the same thing, you pick one name and use it everywhere.

Real-life example: "Male", "M", "m" all become "Male".

School example: "Absent", "A", "a" all become "Absent".

Home example: "Phone", "tel", "mobile" all become "Phone".

Nigerian example: "Naira", "NGN", "₦" all become "Naira".

How to do it: Right-click the column, choose "Replace Values", enter what to find and what to replace with.

Illustration:

Before:   After:
+-------+ +-------+
| Status| | Status|
+-------+ +-------+
| Y     | | Yes   |
| N     | | No    |
| y     | | Yes   |
+-------+ +-------+

Mini summary: Replace values to make your data uniform.

Lesson 9: Remove Rows (Top, Bottom, Alternate)

Definition: Remove rows means deleting certain rows from your table.

Why important: Sometimes you only need a portion of data (e.g., first 10 rows for a sample).

Simple explanation: If you have a long queue, you might only talk to the first 5 people.

Real-life example: You have 1000 rows but only want top 100 for testing.

School example: You have a list of 50 students but only need top 5.

Home example: You have a list of 20 groceries but only want the first 3 for a quick check.

Nigerian example: A store in Ibadan has 200 sales records but only wants the latest 10.

How to do it: Home tab → Remove Rows → Remove Top Rows, Remove Bottom Rows, or Remove Alternate Rows.

Illustration:

Before (10 rows)    After Remove Top 3 (7 rows left)
+----+-----+        +----+-----+
| 1  | A   |        | 4  | D   |
| 2  | B   |  ← remove | 5  | E   |
| 3  | C   |  ← remove | 6  | F   |
| 4  | D   |        | 7  | G   |
| 5  | E   |        | 8  | H   |
...                 ...
+----+-----+        +----+-----+

Mini summary: Remove rows you don't need to focus on important data.

Lesson 10: Keep Rows (Top, Bottom, Range)

Definition: Keep rows means you select and keep only certain rows, deleting all others.

Why important: This is the opposite of remove rows. You choose what to keep.

Simple explanation: It's like picking only the red marbles from a bag and leaving the rest.

Real-life example: You have sales data for all months but only want January to March.

School example: You have grades for all subjects but only want Science grades.

Home example: You have a list of all bills but only want electricity bills.

Nigerian example: You have data for all states but only want Lagos and Abuja.

How to do it: Home tab → Keep Rows → Keep Top Rows, Keep Bottom Rows, Keep Range of Rows.

Illustration:

Before (10 rows)    After Keep Top 2 (only 2 rows)
+----+-----+        +----+-----+
| 1  | A   |  ← keep | 1  | A   |
| 2  | B   |  ← keep | 2  | B   |
| 3  | C   |  remove |    |     |
| 4  | D   |  remove |    |     |
...                 ...
+----+-----+        +----+-----+

Mini summary: Keep only the rows that matter to you.

Lesson 11: Fill Down (Copy from above)

Definition: Fill Down copies the value from the cell above to the empty cells below.

Why important: Useful when you have a header that applies to multiple rows (e.g., a category).

Simple explanation: If you have a list of fruits, and "Apple" is written once, you can fill down so all apples have that label.

Real-life example: A sales table where the region is only written in the first row of each region. Fill down to fill all rows.

School example: A class list where the teacher's name is only in the first row. Fill down for all students.

Home example: A chore list where the day is written once. Fill down for all chores on that day.

Nigerian example: A table of LGA's, only the state is written once. Fill down to show state for every LGA.

How to do it: Select the column, go to "Transform" tab, click "Fill" and choose "Down".

Illustration: (See Lesson 3 illustration).

Mini summary: Fill Down copies the upper value to lower empty cells.

Lesson 12: Fill Up (Copy from below)

Definition: Fill Up copies the value from the cell below to the empty cells above.

Why important: Less common but useful when the first row is blank and the data starts later.

Simple explanation: Same as Fill Down but going upwards.

Real-life example: A table where the header is at the bottom. Fill up to move it to the top.

School example: A list where the last row has the correct value for all above.

Home example: A shopping list where the total is at the bottom, fill up to give each item the total.

Nigerian example: A report where the summary is at the bottom, fill up to apply to all.

How to do it: Transform tab → Fill → Up.

Illustration:

Before:      After Fill Up:
+-------+    +-------+
|       |    |  50   |  ← copied from below
|       |    |  50   |
|  50   |    |  50   |
+-------+    +-------+

Mini summary: Fill Up copies the lower value to upper empty cells.

Lesson 13: Combine Cleaning Steps

Definition: This means doing many cleaning actions one after another.

Why important: Real data needs many fixes. You combine them to get a perfect table.

Simple explanation: It's like a recipe: first wash the vegetables, then chop them, then cook them.

Real-life example: A data set: remove duplicates, trim spaces, change types, rename columns.

School example: A grade sheet: remove missing, change text to numbers, sort.

Home example: A budget: replace categories, split amounts, fill missing.

Nigerian example: A COVID-19 data: remove duplicate entries, fix date format, replace missing with "0".

How to do it: In Power Query, each step appears in the "Applied Steps" pane. You can reorder or delete steps.

Illustration: (Flow chart)

   Start
    |
    V
 Remove Duplicates
    |
    V
 Trim Spaces
    |
    V
 Change Data Types
    |
    V
 Rename Columns
    |
    V
   Done

Mini summary: Combine steps to clean data thoroughly.

Lesson 14: Using "Replace Errors"

Definition: Replace Errors changes error values (like #Error) to something else.

Why important: Errors stop calculations. Replacing them with 0 or "Unknown" lets you continue.

Simple explanation: If a math sum gives an error, you can say "let's treat it as zero".

Real-life example: A column has "5/0" which gives error. Replace with 0.

School example: A formula column has errors. Replace with "N/A".

Home example: A budget column has errors. Replace with 0.

Nigerian example: A financial report has division by zero errors. Replace with 0.

How to do it: Right-click the column → Replace Errors → type the replacement value.

Illustration:

Before:   After:
+-------+ +-------+
| #Error| |   0   |
| 10    | |  10   |
+-------+ +-------+

Mini summary: Replace errors to avoid breaking your analysis.

Lesson 15: Pivot and Unpivot (advanced but fun)

Definition: Pivot turns rows into columns. Unpivot turns columns into rows.

Why important: Sometimes data is in a "wide" format, but you need "long" format for analysis.

Simple explanation: If you have a table with months as columns, unpivot makes a "Month" column and a "Value" column.

Real-life example: Sales data with Jan, Feb, Mar as columns. Unpivot to have Month and Sales rows.

School example: A table with subjects as columns. Unpivot to have Subject and Score rows.

Home example: A budget with months as columns. Unpivot for easier charting.

Nigerian example: A table with states as columns. Unpivot to have State and Population rows.

How to do it: Select columns, right-click → Unpivot Columns. Or Pivot on a column.

Illustration:

Wide (Pivot)              Long (Unpivot)
+----+-----+-----+       +----+-------+-------+
|Year| Jan | Feb |       |Year| Month | Sales |
+----+-----+-----+       +----+-------+-------+
|2024| 100 | 150 |  ➡️  |2024| Jan   | 100   |
+----+-----+-----+       |2024| Feb   | 150   |
                          +----+-------+-------+

Mini summary: Pivot/Unpivot reshapes your data for different needs.

📖 Key Vocabulary (with simple definitions)

  • Data Cleaning: Fixing mistakes in data.
  • Duplicate: Two or more identical rows.
  • Missing Value: An empty cell.
  • Split: Divide one column into two.
  • Data Type: The kind of data (text, number, date).
  • Trim: Remove extra spaces.
  • Replace: Change one value to another.
  • Fill Down: Copy value from above.
  • Pivot: Turn rows into columns.
  • Unpivot: Turn columns into rows.

🧠 Important Concepts

  • Garbage in, garbage out: If your data is dirty, your results will be wrong. Clean data leads to correct answers.
  • Step-by-step: Power Query records every cleaning step. You can go back and change any step.
  • Always check data types: A number stored as text cannot be added. Always set the right type.
  • Standardize: Make everything uniform (e.g., all dates in the same format).

🔢 Step-by-Step Explanations

How to remove duplicates:

  1. Select the table.
  2. Go to Home tab.
  3. Click "Remove Rows".
  4. Choose "Remove Duplicates".
  5. Done! All exact duplicate rows are deleted.

How to split a column by delimiter:

  1. Select the column (e.g., "Full Name").
  2. Go to Transform tab.
  3. Click "Split Column".
  4. Choose "By Delimiter".
  5. Select space or comma.
  6. Click OK. Now you have two columns.

🌍 Real-life Examples

  • Banking: Banks clean transaction data to find fraud.
  • Healthcare: Hospitals clean patient records to avoid mistakes.
  • Retail: Stores clean sales data to know what sells best.

🇳🇬 Nigerian Examples

  • NIN Registration: The National Identity Management Commission cleans NIN data to avoid duplicates.
  • Election Results: INEC cleans voter data to ensure accuracy.
  • Market Sales: A trader in Onitsha cleans sales records to know profits.

🎈 Fun Examples Children Can Relate To

  • Toys: Cleaning a list of toys: remove duplicates, fix spellings (e.g., "car" and "kar").
  • Candy: A list of candies with different names for same candy. Replace them all with one name.
  • Friends: A list of friends with extra spaces in names. Trim to make neat.

🏠 Everyday Examples

  • Phone contacts: Cleaning contacts: remove duplicates, fix names.
  • Recipe book: Clean ingredients list: remove duplicates, correct measurements.
  • Homework list: Clean the list of assignments: remove completed ones, add due dates.

👩‍🏫 Teacher Notes

  • Encourage students to practice with real messy data (e.g., a list of names with typos).
  • Use group activities where each group cleans a different dataset.
  • Emphasize that cleaning is often the most time-consuming but most important step.

👨‍👩‍👦 Parent Tips

  • Help your child find messy data at home (e.g., a handwritten grocery list).
  • Discuss why clean data is important (e.g., correct change at the store).
  • Encourage them to use Power Query to clean data for school projects.

💡 Interesting Facts

  • Data scientists spend about 80% of their time cleaning data!
  • Power Query was originally an Excel add-in, now it's built into Excel and Power BI.
  • Cleaning data can save companies millions of dollars by avoiding errors.

❓ Did You Know?

Did you know that the word "data" comes from Latin, meaning "given" (like a gift). But dirty data is not a gift – it's a headache! So we clean it.

🔔 Remember This

  • Always clean your data before analyzing.
  • Power Query records all steps, so you can undo or redo.
  • Check for duplicates, blanks, and wrong data types.

⚠️ Common Mistakes

  • Forgetting to trim spaces – "Ade" and "Ade " are different.
  • Not changing data type – trying to sum text.
  • Removing rows without checking if they are needed.
  • Not replacing errors – leaving #Error in data.

✅ Best Practices

  • Always make a copy of your original data before cleaning.
  • Use descriptive column names.
  • Apply cleaning steps in a logical order (e.g., remove duplicates first, then trim).
  • Check data types after each transformation.

📊 ASCII Illustrations

Data Cleaning Process Flowchart

   Start
    |
    V
 Load Data
    |
    V
 Remove Duplicates
    |
    V
 Replace Missing Values
    |
    V
 Split Columns (if needed)
    |
    V
 Change Data Types
    |
    V
 Trim Spaces
    |
    V
 Rename Columns
    |
    V
   Done 🎉

Comparison: Dirty vs Clean Data

+----------------------------+  +----------------------------+
|      Dirty Data            |  |      Clean Data            |
+----------------------------+  +----------------------------+
| Name: "  Ade "             |  | Name: "Ade"                |
| Age: "25" (text)           |  | Age: 25 (number)           |
| City: "Lagos, Nigeria"     |  | City: "Lagos"              |
|                            |  | Country: "Nigeria"         |
| Duplicate row of Ade       |  | (Duplicate removed)        |
+----------------------------+  +----------------------------+

📋 Comparison Tables

Remove Rows vs Keep Rows

FeatureRemove RowsKeep Rows
What it doesDeletes selected rowsKeeps selected rows, deletes others
Use whenYou want to exclude dataYou want to focus on specific data
ExampleRemove top 5 rowsKeep top 5 rows

Fill Down vs Fill Up

FeatureFill DownFill Up
DirectionCopies from above to belowCopies from below to above
Use whenHeader is at the topHeader is at the bottom
CommonVery commonLess common

📝 End-of-Module Summary

Well done! You have completed Module Seven on Data Cleaning. You learned:

  • What data cleaning is and why it's important.
  • How to remove duplicates, fix missing values, and split columns.
  • How to change data types, rename columns, and trim spaces.
  • How to replace values, remove or keep rows, and fill down/up.
  • How to combine steps and handle errors.
  • How to pivot and unpivot data.

Cleaning data is like being a detective – you find clues (errors) and fix them. Now you are ready to clean any messy data!

❓ Frequently Asked Questions (10)

  1. Why do we need to clean data? – To get correct answers and avoid mistakes.
  2. What is a duplicate row? – A row that is exactly the same as another row.
  3. How do I remove duplicates in Power Query? – Home tab → Remove Rows → Remove Duplicates.
  4. What does "trim" do? – Removes extra spaces from text.
  5. What is a data type? – It tells Power Query if data is text, number, date, etc.
  6. Why can't I sum numbers that are text? – Because text cannot be added. Change to number type.
  7. What is "Fill Down"? – Copies the value from the cell above to empty cells below.
  8. What is "Replace Values"? – Changes one value to another (e.g., "N/A" to "Not Available").
  9. What does "Split Column" do? – Divides one column into two or more columns.
  10. Can I undo a cleaning step? – Yes, Power Query records all steps, so you can delete or reorder them.

📝 Review Questions (15)

  1. What is data cleaning?
  2. Why are duplicates bad?
  3. How do you remove duplicates?
  4. What is a missing value?
  5. How do you fix missing values?
  6. What does splitting a column do?
  7. Give an example of splitting a column.
  8. What is a data type?
  9. Why should you change data types?
  10. What does trimming do?
  11. What is "Replace Values" used for?
  12. What is the difference between "Remove Rows" and "Keep Rows"?
  13. When would you use "Fill Down"?
  14. What is the purpose of "Replace Errors"?
  15. Name three cleaning steps you learned.

✍️ Fill-in-the-Blank Exercises

  1. Data cleaning is the process of finding and fixing ______ in data.
  2. ______ rows are rows that are exactly the same.
  3. ______ removes extra spaces from text.
  4. Changing a column from text to number is changing the ______.
  5. ______ copies the value from the cell above to empty cells below.

✅ True or False Exercises

  1. Data cleaning is not important. (False)
  2. Duplicates are good for analysis. (False)
  3. Trimming removes extra spaces. (True)
  4. You cannot change data types in Power Query. (False)
  5. Fill Down copies from below. (False – it copies from above)

🔘 Multiple Choice Questions (15 with answers)

  1. Which tool removes exact duplicate rows?
    a) Trim b) Remove Duplicates c) Split d) Fill Down
    Answer: b
  2. What does "Trim" do?
    a) Adds spaces b) Removes extra spaces c) Removes duplicates d) Splits columns
    Answer: b
  3. Which data type is used for numbers?
    a) Text b) Date c) Number d) Logical
    Answer: c
  4. What does "Split Column" do?
    a) Combines columns b) Divides one column into two c) Deletes a column d) Renames a column
    Answer: b
  5. What is a missing value?
    a) A value that is too high b) A value that is too low c) An empty cell d) A duplicate
    Answer: c
  6. Which function copies a value from above?
    a) Fill Up b) Fill Down c) Trim d) Split
    Answer: b
  7. Which function changes "N/A" to "Not Available"?
    a) Trim b) Replace Values c) Remove Duplicates d) Split
    Answer: b
  8. What is the first step in data cleaning?
    a) Load data b) Remove duplicates c) Trim d) Split
    Answer: a (load data first)
  9. Which option keeps only the first 5 rows?
    a) Remove Top Rows b) Keep Top Rows c) Remove Duplicates d) Fill Down
    Answer: b
  10. Which option deletes the first 5 rows?
    a) Remove Top Rows b) Keep Top Rows c) Remove Duplicates d) Fill Down
    Answer: a
  11. What does Pivot do?
    a) Turns rows into columns b) Turns columns into rows c) Removes duplicates d) Trims spaces
    Answer: a
  12. What does Unpivot do?
    a) Turns rows into columns b) Turns columns into rows c) Removes duplicates d) Trims spaces
    Answer: b
  13. Which is NOT a data type?
    a) Text b) Number c) Color d) Date
    Answer: c
  14. What is the purpose of "Replace Errors"?
    a) Remove duplicates b) Change error values to something else c) Split columns d) Fill down
    Answer: b
  15. How can you rename a column?
    a) Double-click header b) Remove duplicates c) Split d) Trim
    Answer: a

🔗 Matching Exercises

Match the term to its definition:

TermDefinition
1. TrimA. Copy value from above
2. Fill DownB. Remove extra spaces
3. DuplicateC. Divide one column into two
4. SplitD. Identical row
5. Data TypeE. Kind of data (text, number, date)

Answers: 1-B, 2-A, 3-D, 4-C, 5-E

✍️ Short Answer Questions

  1. Explain why cleaning data is important.
  2. Describe three ways to clean data.
  3. What is the difference between "Remove Rows" and "Keep Rows"?
  4. Give an example of a data type conversion.
  5. Why do we use "Replace Values"?

📖 Scenario-based Exercises

Scenario 1: You have a list of students with names, ages, and grades. Some ages are blank, some names have extra spaces, and there are duplicate rows for a student. What steps would you take to clean this data?

Scenario 2: A store in Lagos has sales data with columns: "Product", "Price (₦)", "Date". The "Price" column has "₦" symbols and spaces. How would you clean this data to calculate total sales?

👥 Group Activity

In groups of 3, download a sample dataset with messy data (or create one). Assign each person a cleaning task: one removes duplicates, one trims and replaces, one changes data types. Then combine the cleaned data.

🧑‍🎓 Individual Activity

Take a messy list of 20 names (some with spaces, duplicates, typos). Use Power Query to clean it: trim, remove duplicates, fix typos, and rename the column. Write down the steps you took.

💬 Classroom Discussion Questions

  • Why do you think data cleaning is often called "data wrangling"?
  • What happens if we skip data cleaning?
  • Can you think of a time when you had to clean something (not data)? How is it similar?

🛠️ Mini Project

Project: Clean a School Dataset

You are given a dataset of 100 students with columns: StudentID, Name, Class, Score. The dataset has duplicates, missing scores, and inconsistent names (some have extra spaces, some are in uppercase/lowercase). Clean the dataset using Power Query. Present the cleaned table in class.

📋 Practical Assignment

Download a CSV file from the internet (e.g., a sample sales dataset). Use Power Query to:

  1. Remove duplicates.
  2. Trim all text columns.
  3. Change data types correctly.
  4. Split any combined columns.
  5. Replace missing values with "0" or "Unknown".
  6. Save the cleaned data as a new CSV.

🏆 Challenge Exercise

You have a dataset with sales for 5 years, each year as a separate column (2019, 2020, 2021, 2022, 2023). Unpivot this data to create a "Year" column and a "Sales" column. Then clean the data: remove any rows with sales less than 0, and replace any missing years with the average of the previous and next year.

📝 Quiz Answers

Fill-in-the-Blank: 1. errors, 2. Duplicate, 3. Trim, 4. data type, 5. Fill Down

True/False: 1-F, 2-F, 3-T, 4-F, 5-F

Matching: 1-B, 2-A, 3-D, 4-C, 5-E

🔑 Key Takeaways

  • Data cleaning is essential for accurate analysis.
  • Power Query provides many tools to clean data easily.
  • Always check for duplicates, blanks, and incorrect data types.
  • Combining cleaning steps creates a powerful data transformation.
  • Practice makes perfect – clean different datasets to become an expert.

📖 Preparation for the Next Module

In Module Eight, we will learn about Combining Data – how to merge and append tables. We will join data from different sources, just like putting puzzle pieces together. Get ready to become a Data Merger!

Before the next class, practice cleaning at least three different datasets. The more you clean, the better you become.


© 2025 Certified Power Query for Data Analysis Expert – Module Seven

9

Module Eight

Module 8 · Power Query for Data Analysis Expert

🧩 Module Eight: Combining Data Like a Puzzle Master

Hello, young data explorer! Welcome to Module Eight. In this module, we will learn how to combine data from different places. Imagine you have two puzzle pieces. Alone, they don't show the whole picture. But when you join them together, you see the complete image. That's what combining data does – it brings together information from different tables to give you a full story. We will learn about merging (like joining two lists side by side) and appending (like stacking one list on top of another). By the end of this module, you will be a Data Puzzle Master!

🎯 Learning Objectives

  • Understand what combining data means.
  • Learn the difference between merging and appending.
  • Learn how to perform a merge (join) in Power Query.
  • Learn about different join types: Inner, Left Outer, Right Outer, Full Outer.
  • Learn how to append (stack) tables.
  • Understand how to combine data from multiple files in a folder.
  • Learn how to use the "Merge" and "Append" buttons in Power Query.
  • Learn how to handle mismatched keys.
  • Understand the importance of a unique identifier (key).
  • Learn how to combine data without losing information.
  • Use combined data for better analysis.

📖 Warm-up Story: The Two Class Lists

Ngozi is the class prefect. She has two lists. List A has student names and their test scores. List B has student names and their project scores. But the lists are separate. Ngozi wants to see each student's total score (test + project). She decides to combine the two lists. She matches each student from List A with the same student in List B. If a student is missing in one list, she writes "Absent". After combining, she has a complete table with all scores. That's what we will do with Power Query – combine tables to see the whole picture!

📚 Main Lessons (15 Lessons)

Lesson 1: What is Combining Data?

Definition: Combining data means taking two or more tables and joining them together.

Why important: Often your data is spread across different files. Combining helps you see everything in one place.

Simple explanation: It's like putting together pieces of a jigsaw puzzle to see the complete picture.

Real-life example: A company has a table of employees and a table of salaries. They combine them to get a full employee record.

School example: You have a list of students and a list of their favourite subjects. Combining gives you a list with both.

Home example: You have a list of family members and a list of their birthdays. Combine to see everyone's birthday.

Nigerian example: A bank has customer account details and transaction history. They combine them to see each customer's transactions.

Illustration:

Table 1 (Students)   +   Table 2 (Scores)   =   Combined Table
+----+-------+          +----+-------+         +----+-------+-------+
| ID | Name  |          | ID | Score |         | ID | Name  | Score |
+----+-------+          +----+-------+         +----+-------+-------+
| 1  | Bola  |          | 1  | 90    |         | 1  | Bola  | 90    |
| 2  | Tunde |          | 2  | 85    |         | 2  | Tunde | 85    |
+----+-------+          +----+-------+         +----+-------+-------+

Mini summary: Combining data brings separate tables together into one.

Lesson 2: Merging vs. Appending

Definition: Merging adds columns from one table to another (side by side). Appending stacks rows from one table to another (top to bottom).

Why important: You need to know which method to use depending on what you want.

Simple explanation: Merging is like adding new clothes to your wardrobe (new columns). Appending is like adding more clothes of the same type (more rows).

Real-life example: Merging: adding phone numbers to a contact list. Appending: adding new contacts to the list.

School example: Merging: adding grades to student names. Appending: adding students from another class.

Home example: Merging: adding prices to grocery items. Appending: adding more grocery items.

Nigerian example: Merging: adding LGA to a list of states. Appending: adding data from another state.

Illustration:

Merging (side by side):
Table A: ID, Name   +   Table B: ID, Age   =   Table C: ID, Name, Age

Appending (top to bottom):
Table A: ID, Name   +   Table B: ID, Name   =   Table C: ID, Name (more rows)

Mini summary: Merge = add columns. Append = add rows.

Lesson 3: Understanding Keys (The Matchmaker)

Definition: A key is a column that uniquely identifies each row (e.g., Student ID).

Why important: When merging, the key tells Power Query how to match rows from the two tables.

Simple explanation: It's like a secret code that two friends use to find each other in a crowd.

Real-life example: In a school, student ID is the key to match students with their grades.

School example: Your admission number is the key.

Home example: Your family member's name is a key to find their age.

Nigerian example: NIN (National Identification Number) is a key to match citizens with their records.

Illustration:

Table 1 (Key = ID)    Table 2 (Key = ID)     Merge on ID
+----+-------+        +----+-------+        +----+-------+-------+
| ID | Name  |        | ID | Score |        | ID | Name  | Score |
+----+-------+        +----+-------+        +----+-------+-------+
| 1  | Bola  |        | 1  | 90    |        | 1  | Bola  | 90    |
| 2  | Tunde |        | 2  | 85    |        | 2  | Tunde | 85    |
+----+-------+        +----+-------+        +----+-------+-------+

Mini summary: A key is a special column that matches rows from different tables.

Lesson 4: Inner Join – Keep Only Matches

Definition: Inner join keeps only rows that have a match in both tables.

Why important: Use this when you only want records that exist in both tables.

Simple explanation: If two friends both have the same secret code, they meet. If one doesn't have it, they don't meet.

Real-life example: You have a list of students and a list of those who paid fees. Inner join gives only students who have paid.

School example: List of subjects and list of teachers. Inner join gives subjects that have a teacher assigned.

Home example: List of family members and list of those who like pizza. Inner join gives family members who like pizza.

Nigerian example: Voter register and election results. Inner join gives only voters who voted.

Illustration:

Table A: ID, Name        Table B: ID, Score
1, Bola                  1, 90
2, Tunde                 3, 88   ← ID 3 not in A
Inner Join on ID → only ID 1 (Bola, 90) because ID 2 in A but not in B? Actually ID 2 in A, not in B, so not kept.
Result: ID 1: Bola, 90

Mini summary: Inner join keeps only rows that appear in both tables.

Lesson 5: Left Outer Join – Keep All from Left

Definition: Left outer join keeps all rows from the left table, and matching rows from the right. If no match, right side is null (empty).

Why important: Use this when you don't want to lose any rows from the main table.

Simple explanation: The left table is the boss. It keeps all its rows. The right table is a friend – if it has a match, it joins; if not, it leaves a blank.

Real-life example: You have a list of all students (left) and test scores (right). You want all students, even if they have no score.

School example: All students and their project scores. You want to see all students, even those who didn't submit a project.

Home example: Family members and their chores. You want all members, even if they have no chore.

Nigerian example: All customers and their orders. You want all customers, even those who haven't ordered.

Illustration:

Left Table: ID, Name       Right Table: ID, Score
1, Bola                    1, 90
2, Tunde                   3, 88
3, Zain
Left Outer Join → all from left:
1, Bola, 90
2, Tunde, null (no score)
3, Zain, null (no score)

Mini summary: Left outer join keeps all rows from the left table.

Lesson 6: Right Outer Join – Keep All from Right

Definition: Right outer join keeps all rows from the right table, and matching rows from the left. If no match, left side is null.

Why important: Use this when the right table is your main focus.

Simple explanation: Now the right table is the boss.

Real-life example: You have a list of products (right) and a list of sales (left). You want all products, even if they have no sales.

School example: Subjects (right) and teachers (left). You want all subjects, even if no teacher assigned.

Home example: Chores (right) and family members (left). You want all chores, even if no one does them.

Nigerian example: States (right) and governors (left). You want all states, even if some have no governor data.

Illustration:

Left Table: ID, Name       Right Table: ID, Score
1, Bola                    1, 90
2, Tunde                   3, 88
                           4, 95
Right Outer Join → all from right:
1, Bola, 90
3, null, 88
4, null, 95

Mini summary: Right outer join keeps all rows from the right table.

Lesson 7: Full Outer Join – Keep All from Both

Definition: Full outer join keeps all rows from both tables. If a row doesn't have a match, the missing side is null.

Why important: Use when you want to see everything from both tables.

Simple explanation: Both tables are bosses. Everyone is included.

Real-life example: You have a list of employees and a list of departments. You want to see all employees and all departments, even if some employees are not assigned to a department.

School example: Students and clubs. You want all students and all clubs.

Home example: Family members and hobbies. You want all members and all hobbies.

Nigerian example: Companies and products. You want all companies and all products.

Illustration:

Left: 1, Bola ; 2, Tunde   Right: 1, 90 ; 3, 88
Full Outer → 
1, Bola, 90
2, Tunde, null
3, null, 88

Mini summary: Full outer join keeps all rows from both tables.

Lesson 8: How to Merge in Power Query

Definition: Merging in Power Query is done using the "Merge Queries" button.

Why important: This is the main tool you will use to combine tables.

Simple explanation: It's like clicking a magic button that joins your tables.

Real-life example: You have two Excel sheets. You merge them to create one.

School example: You have a class list and a grade list. Merge to get grades for each student.

Home example: You have a grocery list and a price list. Merge to get total cost.

Nigerian example: You have a list of LGAs and a list of populations. Merge to have population per LGA.

How to do it: In Power Query, go to the "Home" tab, click "Merge Queries", select the two tables, choose the key column, and select the join type.

Illustration:

Step 1: Home → Merge Queries
Step 2: Select Table 1 and Table 2
Step 3: Choose key column (e.g., ID) from each
Step 4: Choose join type (Inner, Left, etc.)
Step 5: Click OK → new column with nested tables
Step 6: Expand the new column to get the data.

Mini summary: Merge Queries is the tool to combine tables in Power Query.

Lesson 9: Appending in Power Query

Definition: Appending adds rows from one table to another. Both tables must have the same column structure.

Why important: Use this when you have data split across multiple files (e.g., sales by month).

Simple explanation: It's like stacking books on top of each other.

Real-life example: You have sales for January in one file and sales for February in another. Append them to get all sales.

School example: Class A attendance and Class B attendance. Append to get total attendance.

Home example: Expenses for week 1 and week 2. Append to get monthly expenses.

Nigerian example: COVID-19 data for Lagos and COVID-19 data for Abuja. Append to get national data.

How to do it: Home tab → Append Queries → Select the tables to append.

Illustration:

Table A: ID, Name    Table B: ID, Name    Append → 
1, Bola              3, Zain              1, Bola
2, Tunde             4, Amina             2, Tunde
                                          3, Zain
                                          4, Amina

Mini summary: Append stacks rows.

Lesson 10: Combining Data from Multiple Files in a Folder

Definition: Power Query can combine all files in a folder (e.g., all CSV files).

Why important: Saves time when you have many files.

Simple explanation: It's like putting all your toys from different boxes into one big toy box.

Real-life example: A company has daily sales files for a year. Power Query combines them into one table.

School example: You have homework files for each subject. Combine them into one file.

Home example: You have photos from different holidays. Combine them into one album.

Nigerian example: A bank has monthly account statements. Combine them into yearly statement.

How to do it: Get Data → From Folder → Browse to folder → Combine & Transform.

Illustration:

Folder: Sales
   |-- Jan.csv
   |-- Feb.csv
   |-- Mar.csv
      ...
Power Query combines all into one Sales table.

Mini summary: Combine from folder is a powerful way to merge many files.

Lesson 11: Handling Mismatched Keys

Definition: Mismatched keys happen when the key column has different values in the two tables (e.g., "1" vs "01").

Why important: If keys don't match, your merge will be wrong.

Simple explanation: If two friends have different secret codes, they can't find each other.

Real-life example: Student ID in one table is "100" and in another is "00100". They don't match.

School example: Your name is "Tunde" in one list and "Tunde O." in another. Not exactly the same.

Home example: "Dad" in one list and "Father" in another.

Nigerian example: Phone number has different formats (080 vs +23480).

How to fix: Before merging, transform the key columns to be the same (e.g., trim, format, convert to text).

Illustration:

Table A: ID = "001"    Table B: ID = "1"   →   Convert both to text and trim.
Then they match: "001" and "1" are different, so we might need to convert to number: 1 and 1 match.

Mini summary: Always ensure keys match exactly before merging.

Lesson 12: Expanding Nested Tables After Merge

Definition: After a merge, Power Query creates a new column containing nested tables. You need to expand it to see the data.

Why important: Without expanding, you only see the word "Table".

Simple explanation: It's like opening a gift box to see the present inside.

Real-life example: You merged, and you see a column with "Table". Click the expand icon to get the actual data.

School example: You merged grades, and you see "Table". Expand to see scores.

Home example: You merged prices, and you see "Table". Expand to see prices.

Nigerian example: You merged populations, expand to see population numbers.

How to do it: Click the expand icon (two arrows) on the new column header, select the columns you want, and click OK.

Illustration:

After Merge:
+----+-------+-------------+
| ID | Name  | Merged      |
+----+-------+-------------+
| 1  | Bola  | Table       |  ← Click expand
+----+-------+-------------+

After Expand:
+----+-------+-------+
| ID | Name  | Score |
+----+-------+-------+
| 1  | Bola  | 90    |
+----+-------+-------+

Mini summary: Expand nested tables to see the actual data.

Lesson 13: Join with Multiple Columns

Definition: Sometimes you need to match on two or more columns (e.g., First Name and Last Name).

Why important: Single key might not be unique.

Simple explanation: You use two clues to find your friend: name and age.

Real-life example: Match customers by first name and last name together.

School example: Match students by class and roll number.

Home example: Match chores by day and person.

Nigerian example: Match citizens by state and LGA.

How to do it: In the merge dialog, select multiple columns from each table (hold Ctrl to select multiple).

Illustration:

Table A: First, Last, Age   Table B: First, Last, Score
Merge on First AND Last.

Mini summary: You can merge on multiple columns for a better match.

Lesson 14: Fuzzy Matching (Approximate Match)

Definition: Fuzzy matching allows matches even if the key is not exactly the same (e.g., "Bola" and "Bolah").

Why important: Handles typos or slight differences.

Simple explanation: It's like guessing a friend's name even if you spell it a little wrong.

Real-life example: "Ade" and "Adeyemi" might be matched.

School example: "Maths" and "Mathematics" might be matched.

Home example: "Soda" and "Pop" might be matched.

Nigerian example: "Lagos" and "Lag" might be matched.

How to do it: In merge dialog, check "Use fuzzy matching" and adjust similarity threshold.

Illustration:

Table A: "Bola"   Table B: "Bolah"   Fuzzy match → treated as same.

Mini summary: Fuzzy matching helps when data has small differences.

Lesson 15: Combining Data – Best Practices

Definition: Follow these tips for successful data combining.

Why important: Avoids errors and makes your work easier.

Simple explanation: Like following a recipe to bake a perfect cake.

  • Always check your keys – make sure they are clean and match.
  • Know whether you need to merge or append.
  • Test with a small sample first.
  • Use descriptive names for your merged queries.
  • Document your steps.

Illustration:

Best Practice Flow:
1. Clean keys (trim, remove spaces)
2. Decide merge or append
3. Perform merge/append
4. Expand if needed
5. Check result
6. Rename columns

Mini summary: Good planning leads to successful combining.

📖 Key Vocabulary (with simple definitions)

  • Combine: To join two or more things together.
  • Merge: To add columns from one table to another.
  • Append: To add rows from one table to another.
  • Key: A column that uniquely identifies a row (like an ID).
  • Inner Join: Keeps rows that match in both tables.
  • Left Outer Join: Keeps all rows from the left table.
  • Right Outer Join: Keeps all rows from the right table.
  • Full Outer Join: Keeps all rows from both tables.
  • Expand: To show the data inside a nested table.
  • Fuzzy Matching: Approximate matching for slight differences.

🧠 Important Concepts

  • Unique Identifier: Every row should have a unique key for accurate merging.
  • Join Types: Choose the right join type based on what you need to keep.
  • Data Consistency: Ensure key columns have the same data type and format.
  • Expansion: Always expand merged columns to get the actual data.

🔢 Step-by-Step Explanations

How to Merge Two Tables:

  1. Load both tables into Power Query.
  2. Go to Home tab → Merge Queries.
  3. Select the first table and the second table.
  4. Choose the key column from each table.
  5. Select the join type (Inner, Left, etc.).
  6. Click OK.
  7. Click the expand icon on the new column.
  8. Select the columns you want to add.
  9. Click OK. You now have a combined table.

How to Append Two Tables:

  1. Load both tables into Power Query.
  2. Go to Home tab → Append Queries.
  3. Select the tables to append.
  4. Click OK. The rows are stacked.

🌍 Real-life Examples

  • Retail: Merge product details with sales transactions to analyze product performance.
  • Healthcare: Append patient records from different hospitals to get a national view.
  • Finance: Merge customer data with account data for a complete customer profile.

🇳🇬 Nigerian Examples

  • Election: Merge voter register with polling unit data to analyze voting patterns.
  • Agriculture: Append crop production data from all states to get national production.
  • Telecom: Merge call detail records with customer plans to analyze usage.

🎈 Fun Examples Children Can Relate To

  • Toys: Merge a list of toys with a list of prices to get a catalog.
  • Candy: Append candy sales for Monday and Tuesday to get weekly sales.
  • Friends: Merge two lists of friends from different classes to get a combined list.

🏠 Everyday Examples

  • Phonebook: Merge contacts from your school and home.
  • Shopping: Append grocery lists from different trips to see total items.
  • Chores: Merge chore lists for each day into a weekly schedule.

👩‍🏫 Teacher Notes

  • Use analogies like puzzles and Lego blocks to explain combining.
  • Demonstrate with real datasets from Excel.
  • Emphasize the importance of clean keys before merging.

👨‍👩‍👦 Parent Tips

  • Help your child find two lists at home (e.g., grocery items and prices) and merge them.
  • Explain how combining data is like matching socks – you need to find the pairs.

💡 Interesting Facts

  • Power Query can combine data from Excel, CSV, databases, web, and more.
  • Combining data is often called "data integration".
  • Merging is one of the most frequently used operations in Power Query.

❓ Did You Know?

Did you know that Power Query can combine data from thousands of files in a folder in just a few clicks? That's powerful!

🔔 Remember This

  • Merging adds columns, appending adds rows.
  • Always choose the right join type.
  • Keys must match exactly for a perfect merge.
  • Expand nested tables to see the data.

⚠️ Common Mistakes

  • Forgetting to expand after merge – you see "Table" instead of data.
  • Using the wrong join type – losing important rows.
  • Keys not matching – wrong or missing matches.
  • Appending tables with different column names – causes errors.

✅ Best Practices

  • Clean your keys before merging (trim, remove spaces).
  • Use a unique key for each row.
  • Test merge with a small sample first.
  • Rename columns after merging for clarity.

📊 ASCII Illustrations

Merge vs Append

Merge (side by side):
+-------+-------+   +-------+-------+   +-------+-------+-------+
| ID    | Name  |   | ID    | Score |   | ID    | Name  | Score |
+-------+-------+   +-------+-------+   +-------+-------+-------+
| 1     | Bola  |   | 1     | 90    |   | 1     | Bola  | 90    |
| 2     | Tunde |   | 2     | 85    |   | 2     | Tunde | 85    |
+-------+-------+   +-------+-------+   +-------+-------+-------+

Append (top to bottom):
+-------+-------+   +-------+-------+   +-------+-------+
| ID    | Name  |   | ID    | Name  |   | ID    | Name  |
+-------+-------+   +-------+-------+   +-------+-------+
| 1     | Bola  |   | 3     | Zain  |   | 1     | Bola  |
| 2     | Tunde |   | 4     | Amina |   | 2     | Tunde |
+-------+-------+   +-------+-------+   | 3     | Zain  |
                                          | 4     | Amina |
                                          +-------+-------+

Join Types Comparison

Inner Join:   Keeps only matching rows.
Left Outer:   Keeps all from left, matches from right.
Right Outer:  Keeps all from right, matches from left.
Full Outer:   Keeps all from both.

📋 Comparison Tables

Merge vs Append

FeatureMergeAppend
What it addsColumnsRows
RequiresKey columnSame column structure
Use whenYou want to combine different informationYou want to combine same information from different sources

Join Types

Join TypeKeepsUse case
InnerOnly matchesWhen you need only common records
Left OuterAll from leftWhen left table is main
Right OuterAll from rightWhen right table is main
Full OuterAll from bothWhen you need everything

📝 End-of-Module Summary

Congratulations! You have completed Module Eight on Combining Data. You learned:

  • The difference between merging (adds columns) and appending (adds rows).
  • What a key is and why it's important for merging.
  • The four join types: Inner, Left Outer, Right Outer, and Full Outer.
  • How to merge and append in Power Query.
  • How to combine data from multiple files in a folder.
  • How to handle mismatched keys and expand nested tables.
  • Fuzzy matching for approximate matches.

Combining data is like being a master puzzle solver. You take different pieces and put them together to see the big picture. Now you can combine any data with confidence!

❓ Frequently Asked Questions (10)

  1. What is the difference between merge and append? – Merge adds columns, append adds rows.
  2. What is a key? – A unique column that identifies each row.
  3. What is an Inner Join? – Keeps only rows that match in both tables.
  4. What is a Left Outer Join? – Keeps all rows from the left table.
  5. What is a Right Outer Join? – Keeps all rows from the right table.
  6. What is a Full Outer Join? – Keeps all rows from both tables.
  7. Why do I see "Table" after merging? – You need to expand the nested table.
  8. Can I merge on multiple columns? – Yes, select multiple columns as keys.
  9. What is fuzzy matching? – Approximate matching for slight differences.
  10. How do I combine files from a folder? – Use Get Data → From Folder.

📝 Review Questions (15)

  1. What is combining data?
  2. What is the difference between merging and appending?
  3. What is a key?
  4. Name the four join types.
  5. Which join keeps all rows from the left table?
  6. Which join keeps only matching rows?
  7. How do you expand a nested table after merge?
  8. Why should you clean keys before merging?
  9. What is the purpose of appending?
  10. How do you combine all files in a folder?
  11. What is fuzzy matching?
  12. When would you use a Full Outer Join?
  13. What is a unique identifier?
  14. Can you merge on multiple columns? How?
  15. What is the first step before merging?

✍️ Fill-in-the-Blank Exercises

  1. ______ adds columns to a table.
  2. ______ adds rows to a table.
  3. A ______ is a column that uniquely identifies each row.
  4. ______ join keeps only rows that match in both tables.
  5. ______ join keeps all rows from the left table.

✅ True or False Exercises

  1. Merging adds rows. (False)
  2. Appending adds columns. (False)
  3. A key is used to match rows during a merge. (True)
  4. Inner join keeps all rows from both tables. (False – it keeps only matches)
  5. Left Outer join keeps all rows from the left table. (True)

🔘 Multiple Choice Questions (15 with answers)

  1. Which operation adds columns to a table?
    a) Append b) Merge c) Trim d) Split
    Answer: b
  2. Which operation adds rows to a table?
    a) Append b) Merge c) Trim d) Split
    Answer: a
  3. What is a key?
    a) A random number b) A unique identifier c) A date d) A text
    Answer: b
  4. Which join keeps only matching rows?
    a) Inner b) Left Outer c) Right Outer d) Full Outer
    Answer: a
  5. Which join keeps all rows from the left table?
    a) Inner b) Left Outer c) Right Outer d) Full Outer
    Answer: b
  6. Which join keeps all rows from both tables?
    a) Inner b) Left Outer c) Right Outer d) Full Outer
    Answer: d
  7. What do you click to expand a nested table?
    a) Refresh b) Expand icon c) Delete d) Rename
    Answer: b
  8. What is fuzzy matching?
    a) Exact match b) Approximate match c) No match d) Random match
    Answer: b
  9. Which is NOT a join type?
    a) Inner b) Outer c) Middle d) Full Outer
    Answer: c
  10. How do you combine files from a folder?
    a) Append b) Merge c) From Folder d) Split
    Answer: c
  11. What should you do before merging?
    a) Clean keys b) Delete rows c) Add columns d) Save file
    Answer: a
  12. Which join keeps all rows from the right table?
    a) Inner b) Left Outer c) Right Outer d) Full Outer
    Answer: c
  13. What is the purpose of a key?
    a) To sort data b) To identify rows uniquely c) To add columns d) To delete data
    Answer: b
  14. Can you merge on multiple columns?
    a) Yes b) No c) Only if they are numbers d) Only if they are dates
    Answer: a
  15. What happens if keys don't match?
    a) Merge fails b) Wrong matches c) Both a and b d) Nothing
    Answer: c

🔗 Matching Exercises

Match the term to its definition:

TermDefinition
1. MergeA. Add rows
2. AppendB. Add columns
3. KeyC. Approximate match
4. Inner JoinD. Unique identifier
5. Fuzzy MatchingE. Keep only matches

Answers: 1-B, 2-A, 3-D, 4-E, 5-C

✍️ Short Answer Questions

  1. Explain the difference between merging and appending.
  2. What is a key and why is it important?
  3. Describe the four join types.
  4. How do you expand a nested table in Power Query?
  5. What is fuzzy matching and when would you use it?

📖 Scenario-based Exercises

Scenario 1: You have a table of students (ID, Name) and a table of grades (ID, Grade). You want a table with all students and their grades, but some students have no grade. Which join would you use? Write the steps.

Scenario 2: You have sales data for January and February in separate files. Both files have the same columns. How would you combine them? What is this operation called?

👥 Group Activity

In groups, get two sample datasets (e.g., customer data and order data). Decide which join type to use. Perform the merge in Power Query. Present the result to the class.

🧑‍🎓 Individual Activity

Create two small tables in Excel: one with student IDs and names, another with student IDs and scores. Import them into Power Query, perform a Left Outer Join, and expand the result.

💬 Classroom Discussion Questions

  • Why is it important to choose the right join type?
  • What happens if you forget to expand after a merge?
  • Can you think of a real-life situation where you would append data?

🛠️ Mini Project

Project: Combine Sales Data

You have sales data for four quarters (Q1, Q2, Q3, Q4) in separate Excel files. Each file has the same columns: Product, Salesperson, Amount. Combine all four files into one table using Power Query (append). Then, merge this with a product details table (Product, Category) to add category information. Present the final combined table.

📋 Practical Assignment

Download two datasets from the internet (e.g., customer list and purchase history). Use Power Query to:

  1. Clean both datasets (remove duplicates, trim).
  2. Perform an Inner Join on customer ID.
  3. Expand the merged column.
  4. Save the final table.

🏆 Challenge Exercise

You have three tables: Students (ID, Name), Subjects (SubjectID, SubjectName), and Scores (ID, SubjectID, Score). Write the steps to combine all three tables into one table that shows each student's name, subject, and score. Which joins would you use? Perform the steps in Power Query.

📝 Quiz Answers

Fill-in-the-Blank: 1. Merge, 2. Append, 3. key, 4. Inner, 5. Left Outer

True/False: 1-F, 2-F, 3-T, 4-F, 5-T

Matching: 1-B, 2-A, 3-D, 4-E, 5-C

🔑 Key Takeaways

  • Combining data brings different tables together.
  • Merge adds columns, append adds rows.
  • A key is essential for a successful merge.
  • Choose the right join type for your analysis.
  • Always expand nested tables after merging.
  • Clean keys before merging for best results.

📖 Preparation for the Next Module

In Module Nine, we will learn about Grouping and Aggregating data. We will summarize data (like total sales per product) and group rows to get insights. Get ready to become a Data Summarizer!

Before the next class, practice merging and appending with different datasets. Try to combine data from at least two different sources.


© 2025 Certified Power Query for Data Analysis Expert – Module Eight

10

Module Nine

Module 9 · Power Query for Data Analysis Expert

📊 Module Nine: Grouping and Summarizing Data

Hello, young data explorer! Welcome to Module Nine. In this module, we will learn how to group and summarize data. Imagine you have a big bag of colorful candies. You want to know how many red, blue, and green candies you have. You don't count each candy one by one – you group them by color and then count each group. That's what we do with data: we group rows that share something in common (like product type or region) and then we calculate totals, averages, or counts. This helps us see the big picture and make better decisions. By the end of this module, you will be a Data Summarizing Wizard!

🎯 Learning Objectives

  • Understand what grouping and summarizing mean.
  • Learn how to group data by one or more columns.
  • Learn how to perform aggregations: Sum, Average, Count, Min, Max.
  • Learn how to use the "Group By" feature in Power Query.
  • Learn how to add custom aggregations.
  • Understand the difference between grouped and ungrouped data.
  • Learn how to summarize data to answer business questions.
  • Learn how to use grouping for trend analysis.
  • Understand how to group by multiple columns.
  • Learn how to rename aggregated columns.

📖 Warm-up Story: The Candy Shop Inventory

Chidi runs a small candy shop. He has a long list of all the candies he sold. The list shows each sale: candy name, quantity, and price. But Chidi wants to know: "How many of each candy did I sell?" He groups his sales by candy name. Then he sums the quantities for each candy. He also finds the total money made for each candy. Now he can see which candy is the most popular and which makes the most money. That's grouping and summarizing!

📚 Main Lessons (15 Lessons)

Lesson 1: What is Grouping?

Definition: Grouping means putting rows that have the same value in a column into one group.

Why important: Grouping helps us see patterns and totals for each category.

Simple explanation: It's like sorting your toys into groups: cars in one group, dolls in another.

Real-life example: A store groups sales by product to see which product sells the most.

School example: Your teacher groups students by class to count how many are in each class.

Home example: You group your chores by day of the week to see how many you have each day.

Nigerian example: A bank groups customers by state to see which state has the most customers.

Illustration:

Ungrouped Data:
+-------+--------+-------+
| Candy | Qty    | Price |
+-------+--------+-------+
| Lolly | 5      | 10    |
| Choco | 3      | 20    |
| Lolly | 2      | 10    |
| Choco | 4      | 20    |
| Gum   | 6      | 5     |
+-------+--------+-------+

Grouped by Candy:
+-------+--------+-------+
| Candy | Total  | Total |
|       | Qty    | Price |
+-------+--------+-------+
| Lolly | 7      | 30    |
| Choco | 7      | 40    |
| Gum   | 6      | 5     |
+-------+--------+-------+

Mini summary: Grouping organizes data by common values.

Lesson 2: What is Summarizing?

Definition: Summarizing means calculating a single number for a group, like total, average, count, minimum, or maximum.

Why important: Summarizing turns lots of data into simple, useful numbers.

Simple explanation: It's like adding up all your pocket money to know how much you have in total.

Real-life example: Calculate total sales for each product.

School example: Calculate the average test score for each subject.

Home example: Count how many times you ate your favorite meal in a week.

Nigerian example: Find the minimum and maximum temperature in each state.

Illustration:

Summarizing:
Group: Lolly → Total Qty = 7, Total Price = 30
Group: Choco → Total Qty = 7, Total Price = 40
Group: Gum   → Total Qty = 6, Total Price = 5

Mini summary: Summarizing calculates totals, averages, and counts for each group.

Lesson 3: The Group By Feature in Power Query

Definition: The Group By feature in Power Query groups rows and performs aggregations.

Why important: It's the main tool for grouping and summarizing.

Simple explanation: It's a magic button that does all the grouping and summing for you.

Real-life example: You have a sales table. You use Group By to get total sales per product.

School example: You have a grade table. Group By to get average grade per subject.

Home example: You have an expense table. Group By to get total spent on food, transport, etc.

Nigerian example: You have election results. Group By to get total votes per party.

How to do it: In Power Query, go to the "Transform" tab, click "Group By". Choose the column to group by, and select the aggregation (Sum, Average, etc.).

Illustration:

Transform → Group By
+-------------------+
| Group By Window   |
| Group by: Candy   |
| New column: Total |
| Operation: Sum    |
| Column: Qty       |
+-------------------+

Mini summary: Group By is the tool to summarize data in Power Query.

Lesson 4: Sum – Adding Up Numbers

Definition: Sum adds all the numbers in a group.

Why important: To find total sales, total quantity, total anything.

Simple explanation: If you have 2 apples, 3 apples, and 5 apples, sum is 10 apples.

Real-life example: Total sales for each product.

School example: Total marks for each student.

Home example: Total money spent on groceries.

Nigerian example: Total population per state.

How to do it: In Group By, choose Operation: Sum, Column: the number column.

Illustration:

Group: Candy → Sum Qty = 5+2 = 7

Mini summary: Sum adds up numbers in a group.

Lesson 5: Average – Finding the Middle

Definition: Average adds all numbers and divides by the count.

Why important: To find the typical value, like average score or average price.

Simple explanation: If you have 3, 5, and 7, average is (3+5+7)/3 = 5.

Real-life example: Average price of products.

School example: Average test score of a class.

Home example: Average temperature of the week.

Nigerian example: Average rainfall in each state.

How to do it: In Group By, choose Operation: Average.

Illustration:

Group: Candy → Average Price = (10+20+10+20+5)/5 = 13

Mini summary: Average finds the typical value in a group.

Lesson 6: Count – How Many Items?

Definition: Count tells you how many rows are in a group.

Why important: To know how many items, customers, or transactions.

Simple explanation: If you have 5 candies in a group, count is 5.

Real-life example: Number of orders per product.

School example: Number of students in each class.

Home example: Number of times you ate out this week.

Nigerian example: Number of voters per polling unit.

How to do it: In Group By, choose Operation: Count Rows.

Illustration:

Group: Candy → Count = number of rows for that candy.
Lolly has 2 rows, so Count = 2.

Mini summary: Count gives the number of rows in a group.

Lesson 7: Minimum – The Smallest Value

Definition: Minimum finds the smallest number in a group.

Why important: To find the lowest price, smallest size, etc.

Simple explanation: Among 3, 5, and 7, minimum is 3.

Real-life example: Lowest price of a product.

School example: Lowest test score in a class.

Home example: Minimum temperature of the week.

Nigerian example: Minimum salary in each state.

How to do it: In Group By, choose Operation: Minimum.

Illustration:

Group: Candy → Minimum Price = 10 (for Lolly)

Mini summary: Minimum finds the smallest value.

Lesson 8: Maximum – The Largest Value

Definition: Maximum finds the largest number in a group.

Why important: To find the highest price, largest size, etc.

Simple explanation: Among 3, 5, and 7, maximum is 7.

Real-life example: Highest price of a product.

School example: Highest test score in a class.

Home example: Maximum temperature of the week.

Nigerian example: Maximum population in a state.

How to do it: In Group By, choose Operation: Maximum.

Illustration:

Group: Candy → Maximum Price = 20 (for Choco)

Mini summary: Maximum finds the largest value.

Lesson 9: Grouping by Multiple Columns

Definition: You can group by more than one column (e.g., Candy and Color).

Why important: To get more detailed summaries.

Simple explanation: First group by candy, then by color to see each candy's colors.

Real-life example: Group sales by Product and Month.

School example: Group grades by Subject and Teacher.

Home example: Group expenses by Category and Day.

Nigerian example: Group population by State and LGA.

How to do it: In Group By, click "Add Grouping" and select another column.

Illustration:

Group by: Candy, Color
+-------+-------+-------+
| Candy | Color | Total |
+-------+-------+-------+
| Lolly | Red   | 10    |
| Lolly | Blue  | 5     |
| Choco | Brown | 15    |
+-------+-------+-------+

Mini summary: Group by multiple columns for deeper insights.

Lesson 10: Adding Custom Aggregations

Definition: You can add more than one aggregation in the same Group By.

Why important: To get multiple summaries at once (e.g., Total and Average).

Simple explanation: You can get total sales and average sales per group.

Real-life example: Group by Product: get Total Sales, Average Price, and Count.

School example: Group by Subject: get Total Marks, Average Marks, and Highest Marks.

Home example: Group by Category: get Total Spent and Average Cost.

Nigerian example: Group by State: get Total Population, Average Income, and Count of LGAs.

How to do it: In Group By, click "Add Aggregation" to add more operations.

Illustration:

Group by: Candy
+-------+--------+--------+--------+
| Candy | Total  | Average| Count  |
|       | Price  | Price  |        |
+-------+--------+--------+--------+
| Lolly | 30     | 15     | 2      |
| Choco | 40     | 20     | 2      |
+-------+--------+--------+--------+

Mini summary: Add multiple aggregations for a complete summary.

Lesson 11: Renaming Aggregated Columns

Definition: You can give new names to the columns created by Group By.

Why important: To make the column names clear and descriptive.

Simple explanation: Instead of "Sum of Qty", you name it "Total Quantity".

Real-life example: Rename "Average of Price" to "Avg Price".

School example: Rename "Count" to "Number of Students".

Home example: Rename "Maximum" to "Highest Cost".

Nigerian example: Rename "Sum of Population" to "Total Population".

How to do it: In the Group By dialog, type the new name in the "New column name" field.

Illustration:

Before: "Sum of Qty"   After: "Total Quantity"

Mini summary: Rename aggregated columns for clarity.

Lesson 12: Grouping and Sorting

Definition: After grouping, you can sort the groups by the summarized values.

Why important: To see which groups are the highest or lowest.

Simple explanation: Sort products by total sales from highest to lowest.

Real-life example: Find the best-selling product.

School example: Find the subject with the highest average.

Home example: Find the day you spent the most money.

Nigerian example: Find the state with the highest population.

How to do it: After Group By, click the sort icon on the column header.

Illustration:

Sort by Total Sales Descending:
+-------+--------+
| Candy | Total  |
+-------+--------+
| Choco | 40     |
| Lolly | 30     |
| Gum   | 5      |
+-------+--------+

Mini summary: Sort groups to see the top or bottom performers.

Lesson 13: Grouping and Filtering

Definition: You can filter groups based on the summarized values (e.g., only groups with total sales > 100).

Why important: To focus on important groups.

Simple explanation: Only show candies that sold more than 10 pieces.

Real-life example: Show only products with average price above 50.

School example: Show only students with total marks above 80.

Home example: Show only months with total expenses above 1000.

Nigerian example: Show only states with population above 1 million.

How to do it: After Group By, use the filter dropdown on the aggregated column.

Illustration:

Filter: Total Qty > 5
+-------+--------+
| Candy | Total  |
+-------+--------+
| Lolly | 7      |
| Choco | 7      |
+-------+--------+

Mini summary: Filter groups to focus on specific criteria.

Lesson 14: Using Group By to Answer Questions

Definition: Group By helps answer business questions like "What is the best-selling product?"

Why important: It turns data into answers.

Simple explanation: You ask a question, and Group By gives the answer.

Real-life example: "Which product has the highest total sales?" – Group by product, sum sales, sort descending.

School example: "Which subject has the highest average score?" – Group by subject, average score, sort.

Home example: "On which day do I spend the most?" – Group by day, sum expenses, sort.

Nigerian example: "Which state has the most voters?" – Group by state, count voters, sort.

Illustration:

Question: What is the total sales per product?
Answer: Group By Product, Sum Sales.

Mini summary: Group By turns questions into answers.

Lesson 15: Grouping Best Practices

Definition: Tips for effective grouping.

Why important: To avoid mistakes and get accurate summaries.

Simple explanation: Like following a recipe for a perfect dish.

  • Always clean data before grouping (remove duplicates, trim).
  • Choose the right columns to group by.
  • Use meaningful names for aggregated columns.
  • Check that numbers make sense (e.g., totals are positive).
  • Combine grouping with sorting and filtering for better insights.

Illustration:

1. Clean data
2. Choose group columns
3. Select aggregations
4. Name columns
5. Sort/filter as needed

Mini summary: Follow best practices for accurate grouping.

📖 Key Vocabulary (with simple definitions)

  • Group: A set of rows with the same value in a column.
  • Summarize: To calculate a single number for a group (total, average, etc.).
  • Aggregation: A calculation like Sum, Average, Count, Min, Max.
  • Sum: Add all numbers.
  • Average: Sum divided by count.
  • Count: Number of rows.
  • Minimum: Smallest value.
  • Maximum: Largest value.
  • Group By: The Power Query feature to group and summarize.

🧠 Important Concepts

  • Grouping organizes data: It puts similar items together.
  • Summarizing condenses data: It turns many numbers into a few key numbers.
  • Aggregations are the tools: Sum, Average, Count, Min, Max.
  • Group By is the method: The feature in Power Query.

🔢 Step-by-Step Explanations

How to Group and Summarize Data:

  1. Load your data into Power Query.
  2. Go to the "Transform" tab.
  3. Click "Group By".
  4. In the "Group by" dropdown, select the column you want to group by (e.g., Candy).
  5. Under "New column name", type a name for your aggregated column (e.g., Total Qty).
  6. Under "Operation", choose the aggregation (e.g., Sum).
  7. Under "Column", choose the column to aggregate (e.g., Qty).
  8. Click "Add Aggregation" to add more summaries (e.g., Average Price).
  9. Click OK. Your data is now grouped and summarized.

🌍 Real-life Examples

  • Retail: Group sales by product category to see total revenue per category.
  • Healthcare: Group patient visits by month to see trends.
  • Education: Group students by grade level to calculate average test scores.

🇳🇬 Nigerian Examples

  • Election: Group votes by political party to see total votes per party.
  • Agriculture: Group crop yields by state to see which state produces the most.
  • Telecom: Group call data by region to see total call minutes per region.

🎈 Fun Examples Children Can Relate To

  • Toys: Group your toys by type (cars, dolls, balls) and count how many of each.
  • Candy: Group candies by color and sum the total pieces.
  • Friends: Group friends by their favorite sport and count.

🏠 Everyday Examples

  • Budget: Group expenses by category (food, transport, entertainment) and sum each.
  • Chores: Group chores by day and count how many you have each day.
  • School: Group homework by subject and count assignments.

👩‍🏫 Teacher Notes

  • Use real datasets like school grades or store sales.
  • Encourage students to ask questions and use Group By to answer them.
  • Emphasize that grouping is a powerful tool for data analysis.

👨‍👩‍👦 Parent Tips

  • Help your child group items at home (e.g., books by genre, clothes by color).
  • Discuss how grouping helps in everyday life (e.g., sorting laundry).

💡 Interesting Facts

  • Grouping is one of the most used features in data analysis.
  • Power Query can group data from millions of rows in seconds.
  • Summarizing data helps companies make big decisions.

❓ Did You Know?

Did you know that grouping is also called "aggregation" or "roll-up"? It's like rolling up a rug – you make it smaller and more compact.

🔔 Remember This

  • Grouping puts similar things together.
  • Summarizing calculates totals, averages, etc.
  • Use Group By in Power Query to group and summarize.
  • You can group by one or multiple columns.
  • You can add multiple aggregations.

⚠️ Common Mistakes

  • Forgetting to clean data before grouping (duplicates cause wrong counts).
  • Choosing the wrong aggregation (e.g., summing text).
  • Not renaming aggregated columns – leads to confusion.
  • Grouping by too many columns – makes data too detailed.

✅ Best Practices

  • Clean data before grouping.
  • Choose the right level of grouping (not too many, not too few).
  • Give clear names to aggregated columns.
  • Use sorting and filtering to highlight important groups.

📊 ASCII Illustrations

Grouping Process Flowchart

  Start
    |
    V
 Load Data
    |
    V
 Clean Data
    |
    V
 Group By
    |
    V
 Choose Group Column(s)
    |
    V
 Choose Aggregations
    |
    V
 Rename Columns
    |
    V
 Sort / Filter (optional)
    |
    V
   Done 🎉

Grouping by Multiple Columns

+--------+--------+-------+
| State  | LGA    | Pop   |
+--------+--------+-------+
| Lagos  | Ikeja  | 500K  |
| Lagos  | Surulere| 400K |
| Ogun   | Abeokuta| 300K |
| Ogun   | Ijebu  | 200K  |
+--------+--------+-------+

Group by State, LGA → Sum Pop
+--------+--------+-------+
| State  | LGA    | Total |
|        |        | Pop   |
+--------+--------+-------+
| Lagos  | Ikeja  | 500K  |
| Lagos  | Surulere| 400K |
| Ogun   | Abeokuta| 300K |
| Ogun   | Ijebu  | 200K  |
+--------+--------+-------+

📋 Comparison Tables

Aggregation Types

AggregationWhat it doesExample
SumAdds numbersTotal sales
AverageFinds the meanAverage price
CountCounts rowsNumber of orders
MinimumSmallest valueLowest price
MaximumLargest valueHighest score

Group By: Single vs Multiple Columns

Single ColumnMultiple Columns
Less detailedMore detailed
Example: Group by ProductExample: Group by Product and Month
Fewer groupsMore groups

📝 End-of-Module Summary

Congratulations! You have completed Module Nine on Grouping and Summarizing Data. You learned:

  • What grouping and summarizing mean.
  • How to use the Group By feature in Power Query.
  • Five types of aggregations: Sum, Average, Count, Minimum, Maximum.
  • How to group by one or multiple columns.
  • How to add custom aggregations and rename columns.
  • How to sort and filter grouped data.
  • Best practices for accurate grouping.

Grouping and summarizing turn raw data into useful information. Now you can answer any "what is the total?" or "what is the average?" question with ease!

❓ Frequently Asked Questions (10)

  1. What is grouping? – Putting rows with the same value into a group.
  2. What is summarizing? – Calculating totals, averages, etc., for each group.
  3. What is the Group By feature? – A tool in Power Query to group and summarize.
  4. What is Sum? – Adding up numbers in a group.
  5. What is Average? – Sum divided by count.
  6. What is Count? – The number of rows in a group.
  7. What is Minimum? – The smallest value in a group.
  8. What is Maximum? – The largest value in a group.
  9. Can I group by multiple columns? – Yes, you can add more grouping columns.
  10. How do I rename aggregated columns? – Type a new name in the Group By dialog.

📝 Review Questions (15)

  1. What is grouping?
  2. What is summarizing?
  3. What feature in Power Query groups data?
  4. Name five aggregations.
  5. What does Sum do?
  6. What does Average do?
  7. What does Count do?
  8. What does Minimum do?
  9. What does Maximum do?
  10. How do you group by multiple columns?
  11. Why should you rename aggregated columns?
  12. What is the benefit of sorting grouped data?
  13. What is the benefit of filtering grouped data?
  14. Why is it important to clean data before grouping?
  15. Give one real-life use of grouping.

✍️ Fill-in-the-Blank Exercises

  1. ______ puts rows with the same value into a group.
  2. ______ adds all numbers in a group.
  3. ______ finds the middle value of a group.
  4. ______ counts the number of rows in a group.
  5. The ______ feature in Power Query is used for grouping.

✅ True or False Exercises

  1. Grouping is the same as sorting. (False)
  2. Average is the sum divided by count. (True)
  3. Maximum finds the smallest value. (False)
  4. You can group by multiple columns. (True)
  5. Group By is found in the Transform tab. (True)

🔘 Multiple Choice Questions (15 with answers)

  1. Which operation adds up numbers?
    a) Average b) Sum c) Count d) Minimum
    Answer: b
  2. Which operation finds the average?
    a) Sum b) Average c) Count d) Maximum
    Answer: b
  3. Which operation counts rows?
    a) Sum b) Average c) Count d) Minimum
    Answer: c
  4. Which operation finds the smallest value?
    a) Sum b) Average c) Minimum d) Maximum
    Answer: c
  5. Which operation finds the largest value?
    a) Sum b) Average c) Minimum d) Maximum
    Answer: d
  6. What is the tool for grouping in Power Query?
    a) Split b) Merge c) Group By d) Append
    Answer: c
  7. Can you group by more than one column?
    a) Yes b) No c) Only if they are numbers d) Only if they are text
    Answer: a
  8. Why rename aggregated columns?
    a) To make them shorter b) To make them clear c) To delete them d) To sort them
    Answer: b
  9. What is the first step before grouping?
    a) Sort b) Clean data c) Merge d) Append
    Answer: b
  10. Which aggregation is used to find total sales?
    a) Average b) Sum c) Count d) Minimum
    Answer: b
  11. Which aggregation is used to find the most common score?
    a) Sum b) Average c) Count d) None of the above (you need mode, not listed)
    Answer: d (but if forced, Count is not mode)
  12. What does "Count Rows" do?
    a) Counts cells b) Counts rows c) Sums rows d) Averages rows
    Answer: b
  13. How do you add multiple aggregations?
    a) Click "Add Aggregation" b) Click "Add Grouping" c) Click "Add Column" d) Click "Add Row"
    Answer: a
  14. What is the purpose of grouping?
    a) To make data bigger b) To summarize data c) To delete data d) To hide data
    Answer: b
  15. Which tab contains Group By?
    a) Home b) Transform c) View d) Add Column
    Answer: b

🔗 Matching Exercises

Match the aggregation to its description:

AggregationDescription
1. SumA. Smallest value
2. AverageB. Largest value
3. CountC. Add all numbers
4. MinimumD. Sum divided by count
5. MaximumE. Number of rows

Answers: 1-C, 2-D, 3-E, 4-A, 5-B

✍️ Short Answer Questions

  1. What is the difference between grouping and summarizing?
  2. Explain the five aggregations.
  3. How do you group by multiple columns in Power Query?
  4. Why is it important to clean data before grouping?
  5. Give an example of how you would use grouping in real life.

📖 Scenario-based Exercises

Scenario 1: You have a table of sales with columns: Product, Salesperson, Amount. You want to know the total amount sold by each salesperson. How would you do it? Write the steps.

Scenario 2: You have a table of student test scores with columns: Student, Subject, Score. You want to know the average score for each subject. Which aggregation would you use? Write the steps.

👥 Group Activity

In groups, get a dataset of sales (Product, Region, Sales). Use Group By to find total sales per product and per region. Present your findings.

🧑‍🎓 Individual Activity

Create a small table of expenses (Category, Amount). Use Power Query to group by Category and Sum Amount. Also add a Count of expenses per category.

💬 Classroom Discussion Questions

  • Why is grouping important for decision making?
  • What other aggregations would you like to have?
  • How does grouping help in everyday life?

🛠️ Mini Project

Project: Sales Summary

You have a dataset of 500 sales transactions with columns: OrderID, Product, Category, Salesperson, Region, Amount, Date. Use Power Query to:

  1. Group by Product and find Total Amount, Average Amount, and Count of Orders.
  2. Group by Region and find Total Amount.
  3. Group by Category and find Total Amount and Count.
  4. Create a report with all three summaries.

📋 Practical Assignment

Download a sample dataset (e.g., sales data). Use Power Query to group by at least two different columns and perform at least three aggregations. Save the summarized table.

🏆 Challenge Exercise

You have a dataset with columns: Product, Month, Sales. Group by Product and Month, then calculate Total Sales. Then, for each product, find the month with the highest sales. Use grouping and sorting to achieve this.

📝 Quiz Answers

Fill-in-the-Blank: 1. Grouping, 2. Sum, 3. Average, 4. Count, 5. Group By

True/False: 1-F, 2-T, 3-F, 4-T, 5-T

Matching: 1-C, 2-D, 3-E, 4-A, 5-B

🔑 Key Takeaways

  • Grouping organizes data into categories.
  • Summarizing calculates key numbers for each category.
  • Use Group By in Power Query for easy grouping and summarizing.
  • Five main aggregations: Sum, Average, Count, Min, Max.
  • Group by one or multiple columns for different levels of detail.
  • Always clean data and rename columns for clarity.

📖 Preparation for the Next Module

In Module Ten, we will learn about Pivot and Unpivot – how to reshape your data from wide to long and vice versa. This will help you prepare data for charts and deeper analysis. Get ready to twist and turn your data!

Before the next class, practice grouping and summarizing with different datasets. Try to answer at least three business questions using grouping.


© 2025 Certified Power Query for Data Analysis Expert – Module Nine

11

Module Ten

Module 10 · Power Query for Data Analysis Expert

🔄 Module Ten: Pivot and Unpivot – Reshaping Data

Hello, young data explorer! Welcome to Module Ten. In this module, we will learn how to reshape our data. Sometimes data is in a "wide" format (many columns) and sometimes in a "long" format (many rows). We need to change from one to the other. This is called pivoting and unpivoting. Imagine you have a table where each month is a column. Unpivot turns those month columns into rows. Pivot does the opposite – it turns rows into columns. This helps us prepare data for charts and reports. By the end of this module, you will be a Data Reshaping Master!

🎯 Learning Objectives

  • Understand what pivot and unpivot mean.
  • Learn the difference between wide and long data.
  • Learn how to unpivot columns into rows.
  • Learn how to pivot rows into columns.
  • Learn how to use the "Unpivot Columns" feature.
  • Learn how to use the "Pivot Column" feature.
  • Understand when to use pivot and when to use unpivot.
  • Learn how to handle multiple value columns.
  • Learn how to rename pivoted columns.
  • Use pivot and unpivot for better analysis.

📖 Warm-up Story: The Monthly Sales Puzzle

Chidi has a sales table with months as columns: January, February, March. He wants to create a chart, but the chart expects months in a single column. So he unpivots the data – he turns the month columns into rows. Now he has a "Month" column and a "Sales" column. He can now make a beautiful chart. Later, his teacher wants a summary table with months as columns again. So he pivots the data back. That's the power of pivot and unpivot!

📚 Main Lessons (15 Lessons)

Lesson 1: What is Wide Data?

Definition: Wide data has many columns. Each column represents a different variable (e.g., Jan, Feb, Mar).

Why important: Wide data is easy to read for humans, but not always good for analysis.

Simple explanation: It's like a big table where each month has its own column.

Real-life example: A table with sales for each month as separate columns.

School example: A table with subjects as columns and student scores as rows.

Home example: A table with days of the week as columns and chores as rows.

Nigerian example: A table with states as columns and population as rows.

Illustration:

Wide Data (Months as columns)
+--------+-----+-----+-----+
| Product| Jan | Feb | Mar |
+--------+-----+-----+-----+
| Choco  | 100 | 150 | 200 |
| Lolly  | 50  | 60  | 70  |
+--------+-----+-----+-----+

Mini summary: Wide data has many columns.

Lesson 2: What is Long Data?

Definition: Long data has fewer columns but many rows. One column identifies the variable (e.g., Month), and another holds the value (e.g., Sales).

Why important: Long data is great for charts and analysis.

Simple explanation: It's like a tall table where months are in a single column.

Real-life example: A table with a "Month" column and a "Sales" column.

School example: A table with "Subject" and "Score" columns.

Home example: A table with "Day" and "Expense" columns.

Nigerian example: A table with "State" and "Population" columns.

Illustration:

Long Data (Month in one column)
+--------+-------+-------+
| Product| Month | Sales |
+--------+-------+-------+
| Choco  | Jan   | 100   |
| Choco  | Feb   | 150   |
| Choco  | Mar   | 200   |
| Lolly  | Jan   | 50    |
| Lolly  | Feb   | 60    |
| Lolly  | Mar   | 70    |
+--------+-------+-------+

Mini summary: Long data has few columns but many rows.

Lesson 3: What is Unpivot?

Definition: Unpivot turns columns into rows. It takes wide data and makes it long.

Why important: Unpivot prepares data for charts and analysis.

Simple explanation: It's like taking a wide table and stacking it into a tall table.

Real-life example: Turning monthly sales columns into a Month column and a Sales column.

School example: Turning subject columns into a Subject column and a Score column.

Home example: Turning day columns into a Day column and a Chore column.

Nigerian example: Turning state columns into a State column and a Population column.

How to do it: Select the columns you want to unpivot, right-click, and choose "Unpivot Columns".

Illustration:

Wide → Unpivot → Long
+--------+-----+-----+-----+   +--------+-------+-------+
| Product| Jan | Feb | Mar |   | Product| Month | Sales |
+--------+-----+-----+-----+   +--------+-------+-------+
| Choco  | 100 | 150 | 200 |   | Choco  | Jan   | 100   |
| Lolly  | 50  | 60  | 70  |   | Choco  | Feb   | 150   |
+--------+-----+-----+-----+   | Choco  | Mar   | 200   |
                                | Lolly  | Jan   | 50    |
                                | Lolly  | Feb   | 60    |
                                | Lolly  | Mar   | 70    |
                                +--------+-------+-------+

Mini summary: Unpivot turns columns into rows.

Lesson 4: How to Unpivot in Power Query

Definition: In Power Query, you can unpivot by selecting columns and using the "Unpivot Columns" option.

Why important: This is the main way to reshape data in Power Query.

Simple explanation: It's like clicking a button to change a wide table into a long table.

Real-life example: You have a table with months as columns. You unpivot to get a Month column.

School example: You have a table with subjects as columns. You unpivot to get a Subject column.

Home example: You have a table with days as columns. You unpivot to get a Day column.

Nigerian example: You have a table with states as columns. You unpivot to get a State column.

How to do it: Select the columns (e.g., Jan, Feb, Mar) → right-click → Unpivot Columns.

Illustration:

Select Jan, Feb, Mar → Right-click → Unpivot Columns

Mini summary: Use Unpivot Columns to turn columns into rows.

Lesson 5: Unpivot Other Columns (Keep Some Columns)

Definition: You can unpivot some columns while keeping others as identifiers (e.g., Product).

Why important: You often want to keep some columns as "keys" while unpivoting others.

Simple explanation: You keep the "Product" column as is, and unpivot the month columns.

Real-life example: Keep Product and Region, unpivot monthly sales.

School example: Keep Student Name, unpivot subject scores.

Home example: Keep Family Member, unpivot daily chores.

Nigerian example: Keep LGA, unpivot monthly rainfall.

How to do it: Select the columns to unpivot, right-click, and choose "Unpivot Columns". The other columns stay as identifiers.

Illustration:

Keep Product, unpivot Jan, Feb, Mar.
Result: Product, Attribute (Month), Value (Sales).

Mini summary: Unpivot specific columns while keeping others as identifiers.

Lesson 6: What is Pivot?

Definition: Pivot turns rows into columns. It takes long data and makes it wide.

Why important: Pivot helps create summary tables that are easy to read.

Simple explanation: It's like taking a tall table and spreading it out into a wide table.

Real-life example: Turning a Month column into separate columns for each month.

School example: Turning a Subject column into separate columns for each subject.

Home example: Turning a Day column into separate columns for each day.

Nigerian example: Turning a State column into separate columns for each state.

How to do it: In Power Query, select the column you want to pivot, go to Transform, and click "Pivot Column".

Illustration:

Long → Pivot → Wide
+--------+-------+-------+   +--------+-----+-----+-----+
| Product| Month | Sales |   | Product| Jan | Feb | Mar |
+--------+-------+-------+   +--------+-----+-----+-----+
| Choco  | Jan   | 100   |   | Choco  | 100 | 150 | 200 |
| Choco  | Feb   | 150   |   | Lolly  | 50  | 60  | 70  |
| Choco  | Mar   | 200   |   +--------+-----+-----+-----+
| Lolly  | Jan   | 50    |
| Lolly  | Feb   | 60    |
| Lolly  | Mar   | 70    |
+--------+-------+-------+

Mini summary: Pivot turns rows into columns.

Lesson 7: How to Pivot in Power Query

Definition: In Power Query, you pivot using the "Pivot Column" feature.

Why important: This is the main way to make wide tables from long tables.

Simple explanation: You choose a column whose values will become new columns.

Real-life example: You have a Month column. Pivot it to get columns for each month.

School example: You have a Subject column. Pivot it to get columns for each subject.

Home example: You have a Day column. Pivot it to get columns for each day.

Nigerian example: You have a State column. Pivot it to get columns for each state.

How to do it: Select the column to pivot (e.g., Month) → Transform → Pivot Column → Choose the values column (e.g., Sales).

Illustration:

Select Month → Pivot Column → Values: Sales → OK

Mini summary: Use Pivot Column to turn rows into columns.

Lesson 8: Pivot with Multiple Value Columns

Definition: You can pivot with more than one value column (e.g., Sales and Quantity).

Why important: Sometimes you need to pivot multiple measures.

Simple explanation: You can have both Sales and Quantity as values.

Real-life example: Pivot Month to get Sales and Quantity columns.

School example: Pivot Subject to get Score and Attendance.

Home example: Pivot Day to get Expenses and Calories.

Nigerian example: Pivot Year to get Population and GDP.

How to do it: In Pivot dialog, select "Advanced" and add multiple value columns.

Illustration:

Pivot Month, Values: Sales, Quantity
Result: Jan_Sales, Jan_Qty, Feb_Sales, Feb_Qty, ...

Mini summary: Pivot can handle multiple value columns.

Lesson 9: Unpivot vs Pivot – When to Use Each

Definition: Unpivot makes data longer (more rows). Pivot makes data wider (more columns).

Why important: Choosing the right one depends on your goal.

Simple explanation: Unpivot when you need data for charts. Pivot when you need summary tables.

Real-life example: Unpivot for a line chart. Pivot for a summary report.

School example: Unpivot to compare scores. Pivot to show scores per subject.

Home example: Unpivot to track daily habits. Pivot to see weekly totals.

Nigerian example: Unpivot to analyze monthly trends. Pivot to show state-wise data.

Illustration:

Unpivot: Wide → Long (for charts)
Pivot:   Long → Wide (for summary)

Mini summary: Unpivot for analysis, Pivot for presentation.

Lesson 10: Renaming Pivot Columns

Definition: After pivoting, you may want to rename the new columns.

Why important: To make column names clear and meaningful.

Simple explanation: Change "Jan" to "January Sales".

Real-life example: Rename "Jan" to "Jan-2025".

School example: Rename "Math" to "Math Score".

Home example: Rename "Monday" to "Monday Chores".

Nigerian example: Rename "Lagos" to "Lagos Population".

How to do it: Double-click the column header and type the new name.

Illustration:

Before: "Jan"   After: "January Sales"

Mini summary: Rename pivoted columns for clarity.

Lesson 11: Unpivot with Multiple Identifier Columns

Definition: You can keep multiple columns as identifiers when unpivoting.

Why important: Sometimes you need to keep more than one key column.

Simple explanation: Keep Product and Region, unpivot months.

Real-life example: Keep Product and Region, unpivot monthly sales.

School example: Keep Student and Class, unpivot subject scores.

Home example: Keep Family Member and Day, unpivot meals.

Nigerian example: Keep State and LGA, unpivot monthly rainfall.

How to do it: Select the columns to unpivot, the others stay as identifiers.

Illustration:

Identifiers: Product, Region   Unpivot: Jan, Feb, Mar
Result: Product, Region, Month, Sales

Mini summary: You can have multiple identifier columns when unpivoting.

Lesson 12: Pivot with Advanced Options

Definition: Pivot has advanced options like aggregating values (e.g., Sum, Average).

Why important: If there are duplicate values, you need to aggregate.

Simple explanation: If you have two sales for the same month, sum them.

Real-life example: Sum sales for each month-product combination.

School example: Average scores for each subject-student combination.

Home example: Sum expenses for each day-category combination.

Nigerian example: Sum population for each state-LGA combination.

How to do it: In Pivot dialog, choose "Advanced" and select an aggregation.

Illustration:

Pivot Month, Values: Sales, Aggregation: Sum

Mini summary: Use advanced pivot options for aggregating.

Lesson 13: Unpivot – Handling Errors

Definition: Sometimes unpivot fails if columns have different data types.

Why important: To avoid errors, ensure all columns have the same data type.

Simple explanation: Make sure all month columns are numbers or all are text.

Real-life example: Jan is number, Feb is text – error. Fix by changing types.

School example: Math is number, English is text – error. Fix.

Home example: Monday is number, Tuesday is text – error. Fix.

Nigerian example: Lagos is number, Abuja is text – error. Fix.

How to fix: Change all columns to the same data type before unpivoting.

Illustration:

Before: Jan (number), Feb (text) → Error
Fix: Change both to number → Unpivot works.

Mini summary: Ensure columns have the same data type before unpivoting.

Lesson 14: Combining Pivot and Unpivot

Definition: You can pivot and then unpivot, or vice versa, to reshape data.

Why important: Sometimes you need multiple transformations.

Simple explanation: You might unpivot, clean data, then pivot back.

Real-life example: Unpivot to fix data, then pivot to create summary.

School example: Unpivot to analyze, then pivot to present.

Home example: Unpivot to track, then pivot to report.

Nigerian example: Unpivot for trends, then pivot for comparison.

Illustration:

Wide → Unpivot → Clean → Pivot → Wide (clean version)

Mini summary: Combine pivot and unpivot for powerful reshaping.

Lesson 15: Best Practices for Pivot and Unpivot

Definition: Tips to use pivot and unpivot effectively.

Why important: To avoid errors and get the desired shape.

Simple explanation: Like following a recipe for perfect cookies.

  • Before unpivoting, ensure all columns have the same data type.
  • Choose the right identifier columns.
  • Rename columns after pivoting.
  • Use advanced aggregation if needed.
  • Test with a small sample first.

Illustration:

1. Check data types
2. Select identifiers
3. Choose pivot/unpivot
4. Rename columns
5. Verify result

Mini summary: Follow best practices for smooth reshaping.

📖 Key Vocabulary (with simple definitions)

  • Wide Data: Data with many columns.
  • Long Data: Data with many rows.
  • Unpivot: Turn columns into rows.
  • Pivot: Turn rows into columns.
  • Identifier: A column that stays as is (like Product).
  • Value Column: The column that contains the numbers (like Sales).
  • Attribute Column: The column created by unpivot that holds the original column names (like Month).

🧠 Important Concepts

  • Unpivot makes data longer (good for charts).
  • Pivot makes data wider (good for reports).
  • Identifiers are columns you keep.
  • Value columns are the data you pivot/unpivot.

🔢 Step-by-Step Explanations

How to Unpivot Data:

  1. Load your wide data into Power Query.
  2. Select the columns you want to unpivot (e.g., Jan, Feb, Mar).
  3. Right-click and choose "Unpivot Columns".
  4. You will get an "Attribute" column (the original column names) and a "Value" column (the numbers).
  5. Rename Attribute to "Month" and Value to "Sales".

How to Pivot Data:

  1. Load your long data into Power Query.
  2. Select the column that will become the new columns (e.g., Month).
  3. Go to Transform → Pivot Column.
  4. Choose the Values column (e.g., Sales).
  5. Choose aggregation if needed (e.g., Sum).
  6. Click OK. Now you have a wide table.

🌍 Real-life Examples

  • Retail: Unpivot monthly sales for trend analysis.
  • Healthcare: Pivot patient data to show vitals per day.
  • Education: Unpivot subject scores to calculate average.

🇳🇬 Nigerian Examples

  • Election: Unpivot party votes to compare trends.
  • Agriculture: Pivot crop yields by state for comparison.
  • Telecom: Unpivot monthly call data for analysis.

🎈 Fun Examples Children Can Relate To

  • Toys: Unpivot a table of toy sales by month to see trends.
  • Candy: Pivot a candy sales table to show each candy in its own column.
  • Games: Unpivot scores from different games to compare.

🏠 Everyday Examples

  • Budget: Unpivot monthly expenses to see trends.
  • Chores: Pivot chores by day to see weekly schedule.
  • School: Unpivot subject grades to calculate GPA.

👩‍🏫 Teacher Notes

  • Use real examples like student grades in wide format.
  • Show how unpivoting helps create charts.
  • Emphasize that pivot and unpivot are opposites.

👨‍👩‍👦 Parent Tips

  • Help your child turn a wide table (like a calendar) into a long table.
  • Discuss how reshaping helps in organizing information.

💡 Interesting Facts

  • Pivot and unpivot are also called "transpose" in some tools.
  • Power Query can pivot and unpivot millions of rows quickly.
  • Unpivoting is often the first step in data cleaning.

❓ Did You Know?

Did you know that the term "pivot" comes from sports – pivoting means turning around a fixed point. In data, you turn rows into columns!

🔔 Remember This

  • Unpivot = columns → rows (makes data longer).
  • Pivot = rows → columns (makes data wider).
  • Choose the right operation for your goal.
  • Always check data types before unpivoting.

⚠️ Common Mistakes

  • Forgetting to change data types before unpivoting (causes errors).
  • Pivoting without aggregation when there are duplicates (causes errors).
  • Not renaming columns after pivoting (confusing names).
  • Unpivoting the wrong columns (losing important identifiers).

✅ Best Practices

  • Check data types before unpivoting.
  • Choose the right identifiers.
  • Use aggregation when pivoting with duplicates.
  • Rename columns for clarity.

📊 ASCII Illustrations

Unpivot Process

  Wide Data
+--------+-----+-----+-----+
| Product| Jan | Feb | Mar |
+--------+-----+-----+-----+
| Choco  | 100 | 150 | 200 |
| Lolly  | 50  | 60  | 70  |
+--------+-----+-----+-----+
          |
          V
     Unpivot
          |
          V
  Long Data
+--------+-------+-------+
| Product| Month | Sales |
+--------+-------+-------+
| Choco  | Jan   | 100   |
| Choco  | Feb   | 150   |
| Choco  | Mar   | 200   |
| Lolly  | Jan   | 50    |
| Lolly  | Feb   | 60    |
| Lolly  | Mar   | 70    |
+--------+-------+-------+

Pivot Process

  Long Data
+--------+-------+-------+
| Product| Month | Sales |
+--------+-------+-------+
| Choco  | Jan   | 100   |
| Choco  | Feb   | 150   |
| Choco  | Mar   | 200   |
| Lolly  | Jan   | 50    |
| Lolly  | Feb   | 60    |
| Lolly  | Mar   | 70    |
+--------+-------+-------+
          |
          V
      Pivot
          |
          V
  Wide Data
+--------+-----+-----+-----+
| Product| Jan | Feb | Mar |
+--------+-----+-----+-----+
| Choco  | 100 | 150 | 200 |
| Lolly  | 50  | 60  | 70  |
+--------+-----+-----+-----+

📋 Comparison Tables

Wide vs Long Data

FeatureWideLong
Number of columnsManyFew
Number of rowsFewMany
Best forReports, human readingCharts, analysis

Pivot vs Unpivot

OperationDirectionResult
UnpivotColumns → RowsLonger data
PivotRows → ColumnsWider data

📝 End-of-Module Summary

Congratulations! You have completed Module Ten on Pivot and Unpivot. You learned:

  • The difference between wide and long data.
  • How to unpivot columns into rows.
  • How to pivot rows into columns.
  • When to use each operation.
  • How to handle multiple identifiers and value columns.
  • Best practices to avoid errors.

Pivot and unpivot are powerful tools to reshape data. Now you can transform any data into the perfect shape for your analysis or report!

❓ Frequently Asked Questions (10)

  1. What is wide data? – Data with many columns.
  2. What is long data? – Data with many rows.
  3. What is unpivot? – Turning columns into rows.
  4. What is pivot? – Turning rows into columns.
  5. When should I unpivot? – When you need data for charts or analysis.
  6. When should I pivot? – When you need a summary table.
  7. What is an identifier? – A column you keep as is (like Product).
  8. What is a value column? – The column with the numbers (like Sales).
  9. Why do I need to check data types before unpivoting? – To avoid errors.
  10. Can I pivot with multiple value columns? – Yes, using advanced options.

📝 Review Questions (15)

  1. What is wide data?
  2. What is long data?
  3. What does unpivot do?
  4. What does pivot do?
  5. Give an example of wide data.
  6. Give an example of long data.
  7. When would you use unpivot?
  8. When would you use pivot?
  9. What is an identifier in unpivot?
  10. What is a value column in pivot?
  11. Why should you check data types before unpivoting?
  12. How do you rename columns after pivoting?
  13. What is the "Attribute" column in unpivot?
  14. Can you have multiple identifiers in unpivot?
  15. What is the opposite of unpivot?

✍️ Fill-in-the-Blank Exercises

  1. ______ data has many columns.
  2. ______ data has many rows.
  3. ______ turns columns into rows.
  4. ______ turns rows into columns.
  5. In unpivot, the column that holds the original column names is called ______.

✅ True or False Exercises

  1. Wide data has many rows. (False)
  2. Unpivot makes data longer. (True)
  3. Pivot makes data wider. (True)
  4. You don't need to check data types before unpivoting. (False)
  5. Pivot and unpivot are opposites. (True)

🔘 Multiple Choice Questions (15 with answers)

  1. Which operation turns columns into rows?
    a) Pivot b) Unpivot c) Merge d) Append
    Answer: b
  2. Which operation turns rows into columns?
    a) Pivot b) Unpivot c) Merge d) Append
    Answer: a
  3. What is wide data?
    a) Many columns b) Many rows c) Few columns d) Few rows
    Answer: a
  4. What is long data?
    a) Many columns b) Many rows c) Few columns d) Few rows
    Answer: b
  5. In unpivot, what are the columns you keep called?
    a) Identifiers b) Values c) Attributes d) Measures
    Answer: a
  6. In pivot, what is the column with the numbers called?
    a) Identifier b) Value c) Attribute d) Key
    Answer: b
  7. Why check data types before unpivoting?
    a) To avoid errors b) To make it faster c) To rename columns d) To sort data
    Answer: a
  8. What is the opposite of unpivot?
    a) Merge b) Append c) Pivot d) Split
    Answer: c
  9. Which is best for charts?
    a) Wide b) Long c) Both d) Neither
    Answer: b
  10. Which is best for summary reports?
    a) Wide b) Long c) Both d) Neither
    Answer: a
  11. What is the "Attribute" column in unpivot?
    a) The numbers b) The original column names c) The identifiers d) The totals
    Answer: b
  12. Can you have multiple identifiers in unpivot?
    a) Yes b) No c) Only if they are numbers d) Only if they are text
    Answer: a
  13. Can you pivot with multiple value columns?
    a) Yes b) No c) Only with advanced options d) Only with text
    Answer: a
  14. What happens if you pivot without aggregation when there are duplicates?
    a) Error b) It works fine c) It sums d) It averages
    Answer: a
  15. What is the first step when unpivoting?
    a) Rename columns b) Check data types c) Sort data d) Merge data
    Answer: b

🔗 Matching Exercises

Match the term to its description:

TermDescription
1. Wide DataA. Many rows
2. Long DataB. Many columns
3. UnpivotC. Rows to columns
4. PivotD. Columns to rows

Answers: 1-B, 2-A, 3-D, 4-C

✍️ Short Answer Questions

  1. Explain the difference between wide and long data.
  2. What is unpivot and when would you use it?
  3. What is pivot and when would you use it?
  4. Why is it important to check data types before unpivoting?
  5. Give an example of a pivot operation in real life.

📖 Scenario-based Exercises

Scenario 1: You have a table with months as columns (Jan, Feb, Mar) and products as rows. You want to create a line chart showing sales by month. How would you reshape the data? Write the steps.

Scenario 2: You have a table with a "Month" column and a "Sales" column. You want to present it as a summary table with months as columns. How would you do it? Write the steps.

👥 Group Activity

In groups, get a wide dataset (e.g., sales by month). Unpivot it to long format, then pivot it back to wide. Discuss why you might need to do each operation.

🧑‍🎓 Individual Activity

Create a small wide table (e.g., with months as columns). Use Power Query to unpivot it. Then rename the columns to "Month" and "Sales".

💬 Classroom Discussion Questions

  • Why is unpivoting important for creating charts?
  • How does pivoting help in reporting?
  • Can you think of a situation where you would need to do both?

🛠️ Mini Project

Project: Reshape School Data

You have a wide table of student scores: Student, Math, English, Science, Art. Unpivot the subject columns to create a long table. Then pivot it back to wide, but with subjects as rows and students as columns. Compare the two formats.

📋 Practical Assignment

Download a sample dataset with months as columns (e.g., sales data). Use Power Query to unpivot it. Then create a pivot table in Excel based on the unpivoted data. Submit both the unpivoted table and the pivot table.

🏆 Challenge Exercise

You have a dataset with columns: Product, Year, Quarter, Sales. Pivot the Quarter column to get columns for Q1, Q2, Q3, Q4. Then unpivot the year columns to get a Year column. This is a double transformation – pivot and then unpivot.

📝 Quiz Answers

Fill-in-the-Blank: 1. Wide, 2. Long, 3. Unpivot, 4. Pivot, 5. Attribute

True/False: 1-F, 2-T, 3-T, 4-F, 5-T

Matching: 1-B, 2-A, 3-D, 4-C

🔑 Key Takeaways

  • Wide data = many columns. Long data = many rows.
  • Unpivot = columns → rows (makes data longer).
  • Pivot = rows → columns (makes data wider).
  • Unpivot is great for charts and analysis.
  • Pivot is great for summary tables.
  • Always check data types before unpivoting.
  • Rename columns for clarity.

📖 Preparation for the Next Module

In Module Eleven, we will learn about Advanced Data Transformation – combining multiple techniques to solve complex problems. We will use all the skills from previous modules to clean, combine, group, and reshape data like true experts. Get ready to become a Power Query Master!

Before the next class, practice unpivoting and pivoting with different datasets. Try to create both a chart and a report from the same data.


© 2025 Certified Power Query for Data Analysis Expert – Module Ten

12

Module Eleven

Module 11 · Power Query for Data Analysis Expert

⚡ Module Eleven: Advanced Data Transformation

Hello, young data explorer! Welcome to Module Eleven. In this module, we will learn how to combine everything we have learned so far to perform advanced data transformations. Think of this as the "master chef" level. We will use cleaning, merging, grouping, and reshaping all together to solve complex problems. By the end of this module, you will be a true Power Query expert, able to turn messy data into valuable insights. Let's dive in!

🎯 Learning Objectives

  • Combine multiple transformation steps.
  • Use conditional logic with "Add Conditional Column".
  • Perform complex data type conversions.
  • Create custom columns using M language formulas.
  • Handle errors and exceptions gracefully.
  • Optimize query performance.
  • Use parameters and functions for reusability.
  • Build advanced data pipelines.
  • Automate repetitive transformations.
  • Apply best practices for complex transformations.

📖 Warm-up Story: The Master Chef Challenge

Chidi loves cooking. He wants to cook a big feast for his family. He has many ingredients (raw data). He needs to wash (clean), chop (split), mix (merge), and cook (group) them. He also needs to add special spices (conditional logic) and use a secret recipe (custom formulas). This is exactly what advanced data transformation is about – combining many steps to create a perfect dish (final dataset).

📚 Main Lessons (15 Lessons)

Lesson 1: Building a Transformation Pipeline

Definition: A transformation pipeline is a series of steps applied to data from start to finish.

Why important: Real-world data requires many steps. A pipeline organizes them.

Simple explanation: It's like a recipe: first chop, then cook, then season.

Real-life example: A company gets sales data, cleans it, merges with product data, groups by region, and creates a report.

School example: A teacher takes raw grades, cleans them, calculates averages, and creates a report card.

Home example: You take a messy grocery list, clean it, group by category, and create a shopping plan.

Nigerian example: A bank takes transaction data, cleans it, merges with customer data, and detects fraud.

Illustration:

Transformation Pipeline
   Start
     |
     V
  Load Data
     |
     V
  Clean Data (remove duplicates, trim)
     |
     V
  Merge with other tables
     |
     V
  Group and Summarize
     |
     V
  Pivot/Unpivot (reshape)
     |
     V
  Add Conditional Columns
     |
     V
  Final Dataset

Mini summary: A pipeline is a sequence of transformation steps.

Lesson 2: Conditional Logic with "Add Conditional Column"

Definition: A conditional column creates a new column based on conditions (if this, then that).

Why important: Helps categorize or flag data based on rules.

Simple explanation: If you score above 70, you pass; else, you fail.

Real-life example: If sales > 1000, mark as "High"; else "Low".

School example: If grade > 80, "Excellent"; else "Good".

Home example: If expense > 500, "Major"; else "Minor".

Nigerian example: If rainfall > 100mm, "Heavy"; else "Light".

How to do it: Add Column → Conditional Column → Define rules.

Illustration:

If Score >= 70 then "Pass" else "Fail"
+-------+--------+
| Score | Result |
+-------+--------+
| 85    | Pass   |
| 60    | Fail   |
+-------+--------+

Mini summary: Conditional columns add logic to your data.

Lesson 3: Creating Custom Columns with M Language

Definition: M language is the language behind Power Query. You can write custom formulas.

Why important: When built-in features aren't enough, you can write custom code.

Simple explanation: It's like writing a recipe yourself instead of using a box mix.

Real-life example: Calculate profit = (Price - Cost) * Quantity.

School example: Calculate final grade = (Exam * 0.6) + (Assignment * 0.4).

Home example: Calculate total cost = Price * Quantity + Tax.

Nigerian example: Calculate net salary = Gross - Tax - Pension.

How to do it: Add Column → Custom Column → Write M formula.

Illustration:

= [Price] * [Quantity] - [Discount]

Mini summary: Custom columns allow unlimited transformations.

Lesson 4: Handling Errors with try...otherwise

Definition: try...otherwise handles errors when a formula fails.

Why important: Prevents your query from breaking.

Simple explanation: If something goes wrong, use a backup value.

Real-life example: try [Price] * [Quantity] otherwise 0.

School example: try [Score] / [Total] otherwise 0.

Home example: try [Amount] - [Discount] otherwise 0.

Nigerian example: try [Salary] / [Months] otherwise 0.

How to do it: In custom column, use try...otherwise.

Illustration:

= try [Price] * [Quantity] otherwise 0

Mini summary: try...otherwise prevents errors.

Lesson 5: Using Parameters to Make Queries Flexible

Definition: A parameter is a variable that you can change to alter query results.

Why important: Makes your query reusable for different inputs.

Simple explanation: It's like a knob you can turn to adjust the output.

Real-life example: A parameter for "Year" to filter data for different years.

School example: A parameter for "Class" to get data for a specific class.

Home example: A parameter for "Month" to see expenses for that month.

Nigerian example: A parameter for "State" to filter data by state.

How to do it: Home → Manage Parameters → Create parameter.

Illustration:

Parameter: Year = 2025
Query filters data for Year = [Year]

Mini summary: Parameters make queries flexible.

Lesson 6: Creating Functions for Reusability

Definition: A function is a piece of code that you can reuse multiple times.

Why important: Saves time and reduces errors.

Simple explanation: It's like a stamp – you can stamp the same design many times.

Real-life example: A function to clean text (trim, lowercase) that you apply to many columns.

School example: A function to calculate grade (A, B, C) for any score.

Home example: A function to convert currency.

Nigerian example: A function to format NIN numbers.

How to do it: Create a new blank query, write M code, and turn it into a function.

Illustration:

(Score) => if Score >= 70 then "Pass" else "Fail"

Mini summary: Functions are reusable code blocks.

Lesson 7: Optimizing Performance

Definition: Performance means how fast your query runs.

Why important: Slow queries waste time. Fast queries are efficient.

Simple explanation: It's like a race car – you want it to go fast.

Real-life example: A company with millions of rows needs fast queries.

School example: A teacher with many students wants quick reports.

Home example: You want your budget to update quickly.

Nigerian example: A bank with many transactions needs fast analysis.

Tips: Remove unnecessary columns early, filter data early, and avoid heavy operations.

Illustration:

Before: Load all columns → Filter → Group (slow)
After: Filter → Remove columns → Group (fast)

Mini summary: Optimize queries for speed.

Lesson 8: Combining Multiple Queries

Definition: You can reference one query from another to build complex pipelines.

Why important: Keeps your work organized and modular.

Simple explanation: It's like building with Lego – you combine small blocks to make a big structure.

Real-life example: Query A cleans sales data, Query B merges with product data.

School example: Query A cleans grades, Query B calculates averages.

Home example: Query A cleans expenses, Query B groups by category.

Nigerian example: Query A cleans election data, Query B combines with voter data.

How to do it: Right-click a query → Reference to create a new query based on it.

Illustration:

Query1: Raw Data
Query2: Clean Data (references Query1)
Query3: Final Report (references Query2)

Mini summary: Reference queries to build modular pipelines.

Lesson 9: Using "Group By" with Custom Aggregations

Definition: Custom aggregations go beyond Sum, Average, etc. You can write your own.

Why important: Sometimes you need special calculations.

Simple explanation: Instead of just sum, you can calculate weighted average.

Real-life example: Calculate weighted average price per product.

School example: Calculate GPA (Grade Point Average).

Home example: Calculate average cost per item after discount.

Nigerian example: Calculate voter turnout percentage per state.

How to do it: In Group By, choose "All Rows" as aggregation, then write custom code.

Illustration:

= Table.AddColumn(Grouped, "Weighted Avg", each List.Average([Sales]))

Mini summary: Custom aggregations give you flexibility.

Lesson 10: Merging with Different Join Types

Definition: You can use Inner, Left, Right, and Full Outer joins in the same pipeline.

Why important: Different joins are useful for different scenarios.

Simple explanation: You choose the right join for the job.

Real-life example: Inner join for customers who have orders, Left join for all customers.

School example: Inner join for students with grades, Left join for all students.

Home example: Inner join for family members with chores, Left join for all members.

Nigerian example: Inner join for voters who voted, Left join for all voters.

How to do it: In Merge dialog, choose the join type.

Illustration:

Merge Type: Left Outer (keeps all from left)

Mini summary: Choose join types strategically.

Lesson 11: Advanced Date and Time Transformations

Definition: Extract parts of dates (year, month, day) or calculate differences.

Why important: Date analysis is common in many fields.

Simple explanation: You can find the difference between two dates in days.

Real-life example: Calculate days since last purchase.

School example: Calculate student age from date of birth.

Home example: Calculate days until a bill is due.

Nigerian example: Calculate days since COVID-19 vaccination.

How to do it: Add Column → Date → choose an option.

Illustration:

= Date.Year([Date])
= Date.Month([Date])
= Date.Day([Date])
= Duration.Days([End] - [Start])

Mini summary: Work with dates easily.

Lesson 12: Text Manipulation for Cleaning

Definition: Extract parts of text, replace, or combine text.

Why important: Text data is often messy and needs cleaning.

Simple explanation: You can take first name from full name.

Real-life example: Extract first name from "Chidi Okonkwo".

School example: Extract initials from student names.

Home example: Combine first and last name.

Nigerian example: Extract LGA from address string.

How to do it: Add Column → Text → choose an option.

Illustration:

= Text.Middle([Name], 0, 5)   // first 5 characters
= Text.Replace([Name], " ", "_")
= Text.Upper([Name])

Mini summary: Clean text data effectively.

Lesson 13: Using "Keep Range" and "Remove Range"

Definition: Keep or remove a specific range of rows (e.g., rows 10 to 20).

Why important: Sometimes you need only a subset of rows.

Simple explanation: It's like taking a slice of a cake.

Real-life example: Keep top 10 best-selling products.

School example: Keep students who scored above 80.

Home example: Keep expenses above 1000.

Nigerian example: Keep states with population above 1 million.

How to do it: Home → Keep Rows → Keep Range / Remove Range.

Illustration:

Keep Range: Start 5, End 10

Mini summary: Keep or remove specific rows.

Lesson 14: Using "Fill Down" with Conditional Logic

Definition: Fill Down copies values from above, but you can combine it with conditions.

Why important: Helps fill missing data intelligently.

Simple explanation: If a cell is blank, fill it with the value above, but only if some condition is met.

Real-life example: Fill missing region names based on state.

School example: Fill missing teacher names based on class.

Home example: Fill missing day names based on date.

Nigerian example: Fill missing LGA names based on state.

How to do it: Transform → Fill → Down, then apply a conditional step.

Illustration:

Fill Down, then conditional replace if value is "Unknown".

Mini summary: Combine Fill Down with conditions.

Lesson 15: Documenting Your Query

Definition: Add comments and descriptions to your steps.

Why important: Helps others understand your work.

Simple explanation: It's like leaving notes for yourself and others.

Real-life example: Add a comment explaining why you removed certain rows.

School example: Add a comment explaining a calculation.

Home example: Add a comment explaining your budget rules.

Nigerian example: Add a comment explaining data sources.

How to do it: In the "Applied Steps" pane, right-click a step and choose "Properties".

Illustration:

Step: Removed Duplicates (Comment: "Removed duplicate entries based on Order ID")

Mini summary: Document your query for clarity.

📖 Key Vocabulary (with simple definitions)

  • Pipeline: A series of transformation steps.
  • Conditional Logic: If-then-else rules.
  • M Language: The language used in Power Query.
  • Parameter: A variable that can change.
  • Function: Reusable code.
  • Performance: Speed of query execution.
  • Modular: Breaking work into small, reusable parts.
  • Documentation: Notes and explanations.

🧠 Important Concepts

  • Advanced transformations combine many techniques.
  • Conditional logic adds intelligence to data.
  • Custom columns and functions provide unlimited flexibility.
  • Parameters make queries reusable.
  • Documentation is essential for collaboration.

🔢 Step-by-Step Explanations

How to Add a Conditional Column:

  1. Go to Add Column → Conditional Column.
  2. Name the column (e.g., "Performance").
  3. Define rule: If Score >= 70 then "Pass" else "Fail".
  4. Click OK.

How to Create a Parameter:

  1. Go to Home → Manage Parameters → New.
  2. Name it (e.g., "Year").
  3. Set type (e.g., Number).
  4. Set value (e.g., 2025).
  5. Use it in a filter: [Year] = Year.

🌍 Real-life Examples

  • Retail: Clean sales data, merge with product details, group by category, and create a dashboard.
  • Healthcare: Clean patient records, merge with test results, and flag high-risk patients.
  • Finance: Clean transaction data, merge with customer accounts, and detect unusual patterns.

🇳🇬 Nigerian Examples

  • Election: Clean voter data, merge with polling unit data, and calculate turnout.
  • Agriculture: Clean crop data, merge with weather data, and predict yields.
  • Telecom: Clean call records, merge with customer plans, and analyze usage.

🎈 Fun Examples Children Can Relate To

  • Toys: Clean a toy inventory, merge with prices, group by type, and calculate total value.
  • Candy: Clean candy sales, merge with flavors, group by flavor, and find the most popular.
  • Games: Clean game scores, merge with player names, group by player, and rank players.

🏠 Everyday Examples

  • Budget: Clean monthly expenses, merge with categories, group by category, and create a spending report.
  • Chores: Clean chore lists, merge with family members, group by day, and create a schedule.
  • School: Clean grades, merge with student names, group by subject, and calculate averages.

👩‍🏫 Teacher Notes

  • Use real-world complex datasets.
  • Encourage students to build complete pipelines from start to finish.
  • Emphasize the importance of documentation and performance.

👨‍👩‍👦 Parent Tips

  • Help your child work on a project from beginning to end.
  • Discuss how combining steps is like following a recipe.
  • Encourage them to document their work.

💡 Interesting Facts

  • Power Query can handle millions of rows with good performance.
  • M language is based on the F# programming language.
  • Many large companies use Power Query for daily data preparation.

❓ Did You Know?

Did you know that you can create a "parameter table" to store multiple parameters in a single place? This makes your queries even more powerful!

🔔 Remember This

  • Advanced transformations combine many techniques.
  • Conditional logic adds intelligence.
  • Custom code gives unlimited flexibility.
  • Parameters and functions make queries reusable.
  • Always document your work.

⚠️ Common Mistakes

  • Not documenting steps – makes it hard to understand later.
  • Poor performance – not optimizing queries.
  • Overcomplicating – using complex code when a simple step would do.
  • Not testing – skipping intermediate checks.

✅ Best Practices

  • Plan your pipeline before building it.
  • Test each step individually.
  • Use meaningful names for queries, columns, and steps.
  • Document your work with comments.
  • Optimize performance by reducing data early.

📊 ASCII Illustrations

Complete Transformation Pipeline

   Start
     |
     V
 Load Sales Data
     |
     V
 Clean Data (remove duplicates, trim)
     |
     V
 Merge with Product Data
     |
     V
 Group by Category (Sum Sales)
     |
     V
 Add Conditional Column (High/Low Sales)
     |
     V
 Pivot to Wide Format
     |
     V
 Filter High Sales Only
     |
     V
   Final Report

Conditional Column Example

+--------+----------+----------------+
| Score  | Outcome  | (Conditional)  |
+--------+----------+----------------+
| 85     | Pass     | if Score >= 70 |
| 60     | Fail     | else           |
| 75     | Pass     |                |
+--------+----------+----------------+

📋 Comparison Tables

Conditional vs Custom Column

FeatureConditional ColumnCustom Column
EaseEasy (point-and-click)Requires writing M code
FlexibilityLimited to if-then-elseFull M language
Use caseSimple categorizationComplex calculations

Parameter vs Function

FeatureParameterFunction
What it doesHolds a single valueHolds a reusable piece of code
Use whenYou need to filter or change a valueYou need to repeat a transformation
ExampleYear = 2025CleanText(text) = trim(lower(text))

📝 End-of-Module Summary

Congratulations! You have completed Module Eleven on Advanced Data Transformation. You learned:

  • How to build complete transformation pipelines.
  • How to use conditional logic and custom columns.
  • How to handle errors and optimize performance.
  • How to use parameters and functions for reusability.
  • How to combine all techniques for complex problems.

You are now a true Power Query expert! You can take any messy data and turn it into a clean, useful dataset for analysis.

❓ Frequently Asked Questions (10)

  1. What is a transformation pipeline? – A series of steps applied to data.
  2. What is a conditional column? – A column that uses if-then-else logic.
  3. What is M language? – The programming language in Power Query.
  4. What is a parameter? – A variable that can be changed.
  5. What is a function? – Reusable code.
  6. How can I make my query faster? – Filter and remove columns early.
  7. What is try...otherwise? – A way to handle errors.
  8. Why document my query? – So others can understand it.
  9. What is a custom aggregation? – A special calculation in Group By.
  10. How do I reference another query? – Right-click and choose Reference.

📝 Review Questions (15)

  1. What is a transformation pipeline?
  2. What is a conditional column?
  3. What is M language?
  4. What is a parameter?
  5. What is a function?
  6. How do you handle errors in custom columns?
  7. Why should you optimize performance?
  8. How do you create a custom column?
  9. What is a reference query?
  10. How do you document steps?
  11. What is a custom aggregation?
  12. How do you use try...otherwise?
  13. What is the purpose of parameters?
  14. What is the benefit of functions?
  15. Name three best practices.

✍️ Fill-in-the-Blank Exercises

  1. A ______ is a series of transformation steps.
  2. A ______ column uses if-then-else logic.
  3. ______ is the language behind Power Query.
  4. A ______ is a variable that can be changed.
  5. A ______ is reusable code.

✅ True or False Exercises

  1. A pipeline is a single step. (False)
  2. A conditional column uses if-then-else. (True)
  3. M language is optional. (False)
  4. Parameters make queries flexible. (True)
  5. Functions are not reusable. (False)

🔘 Multiple Choice Questions (15 with answers)

  1. Which feature creates a column based on conditions?
    a) Custom Column b) Conditional Column c) Merge d) Append
    Answer: b
  2. What is M language?
    a) A database b) A programming language c) A file format d) A visualization tool
    Answer: b
  3. What is a parameter?
    a) A fixed value b) A variable c) A table d) A column
    Answer: b
  4. What is a function?
    a) Reusable code b) A single value c) A table d) A column
    Answer: a
  5. How do you handle errors in a custom column?
    a) ignore b) try...otherwise c) delete d) hide
    Answer: b
  6. What is the first step in optimizing performance?
    a) Add columns b) Filter early c) Merge d) Pivot
    Answer: b
  7. How do you reference another query?
    a) Copy-paste b) Right-click → Reference c) Merge d) Append
    Answer: b
  8. What is a custom aggregation?
    a) A built-in function b) A user-defined calculation c) A standard sum d) A pivot
    Answer: b
  9. Why document your query?
    a) To make it slower b) To help others understand c) To delete it d) To hide it
    Answer: b
  10. What is a pipeline?
    a) A single step b) A series of steps c) A table d) A column
    Answer: b
  11. What does try...otherwise do?
    a) Always works b) Handles errors c) Deletes data d) Adds data
    Answer: b
  12. What is the benefit of functions?
    a) Reusability b) Complexity c) Slowness d) Errors
    Answer: a
  13. Which is a best practice?
    a) Skip testing b) Document steps c) Use all columns d) Never filter
    Answer: b
  14. What is a conditional column used for?
    a) Merging tables b) Categorizing data c) Appending rows d) Pivoting
    Answer: b
  15. What is a parameter used for?
    a) Making queries flexible b) Adding columns c) Removing rows d) Changing data types
    Answer: a

🔗 Matching Exercises

Match the term to its description:

TermDescription
1. PipelineA. Reusable code
2. Conditional ColumnB. Variable that can be changed
3. ParameterC. If-then-else logic
4. FunctionD. Series of steps

Answers: 1-D, 2-C, 3-B, 4-A

✍️ Short Answer Questions

  1. What is a transformation pipeline?
  2. Explain the difference between a conditional column and a custom column.
  3. What is the purpose of a parameter?
  4. Why is it important to optimize query performance?
  5. Give an example of when you would use a function.

📖 Scenario-based Exercises

Scenario 1: You have a dataset of sales transactions. You need to clean it, merge with product data, group by product category, and add a column that flags products with sales above 1000 as "High" and below as "Low". Write the steps.

Scenario 2: You have a dataset that is updated monthly. You want to create a parameter for the month so you can easily refresh data for different months. Write the steps to create and use the parameter.

👥 Group Activity

In groups, build a complete transformation pipeline for a sample dataset. Include cleaning, merging, grouping, and adding a conditional column. Document each step and explain your choices.

🧑‍🎓 Individual Activity

Take a messy dataset (e.g., sales data). Build a complete pipeline with at least 5 steps. Include at least one conditional column and one custom column. Document your work.

💬 Classroom Discussion Questions

  • Why is it important to plan your pipeline before building it?
  • How do you decide which steps to include?
  • What are the trade-offs between simplicity and flexibility?

🛠️ Mini Project

Project: Complete Sales Analysis Pipeline

You have sales data, product data, and customer data. Build a complete pipeline that:

  1. Cleans all three datasets.
  2. Merges them into one.
  3. Groups by product category and calculates total sales.
  4. Adds a conditional column to flag high-performing categories.
  5. Pivots the data to show sales by year.
  6. Adds a parameter to filter by region.

📋 Practical Assignment

Download a large dataset (e.g., from Kaggle). Build a complete transformation pipeline with at least 10 steps. Include cleaning, merging, grouping, conditional logic, and custom columns. Document every step.

🏆 Challenge Exercise

Create a function that takes a table and a column name, and returns the table with that column cleaned (trimmed, lowercased). Use this function in a pipeline to clean multiple columns.

📝 Quiz Answers

Fill-in-the-Blank: 1. pipeline, 2. conditional, 3. M, 4. parameter, 5. function

True/False: 1-F, 2-T, 3-F, 4-T, 5-F

Matching: 1-D, 2-C, 3-B, 4-A

🔑 Key Takeaways

  • Advanced transformations combine multiple techniques.
  • Plan your pipeline before building it.
  • Use conditional logic, custom columns, and functions.
  • Optimize performance and document your work.
  • Practice makes perfect – build many pipelines!

📖 Preparation for the Next Module

In Module Twelve, we will learn about Data Integration and Automation – how to connect to live data sources and automate your queries. You will learn how to schedule refreshes and build dataflows. Get ready to become an automation expert!

Before the next class, practice building a complete pipeline with at least 10 steps. Try to use parameters and functions.


© 2025 Certified Power Query for Data Analysis Expert – Module Eleven

13

Module Twelve

Module 12 · Power Query for Data Analysis Expert

🤖 Module Twelve: Data Integration and Automation

Hello, young data explorer! Welcome to Module Twelve. In this module, we will learn how to connect to live data and automate our data updates. Imagine you have a magic machine that fetches new data every day and updates your reports automatically. That's what automation does! You don't have to repeat the same steps again and again. Instead, Power Query does the work for you. By the end of this module, you will be able to build automated data pipelines that save time and effort.

🎯 Learning Objectives

  • Understand what data integration means.
  • Learn how to connect to different data sources (Excel, CSV, databases).
  • Learn how to refresh queries automatically.
  • Understand how to schedule data refreshes.
  • Learn about Power Query Dataflows.
  • Understand the concept of ETL (Extract, Transform, Load).
  • Learn how to handle data source changes.
  • Learn how to use parameters for dynamic connections.
  • Understand how to share queries with others.
  • Build a complete automated data pipeline.

📖 Warm-up Story: The Magic Mailbox

Chidi has a magic mailbox. Every morning, a new letter arrives with sales data. He doesn't have to go to the store to pick it up – it comes automatically. He then reads the letter and updates his sales report. This is exactly what data integration and automation do. Power Query connects to data sources (like the mailbox) and refreshes your reports automatically. You set it up once, and it works forever!

📚 Main Lessons (15 Lessons)

Lesson 1: What is Data Integration?

Definition: Data integration is the process of combining data from different sources into a single, unified view.

Why important: Data is often scattered across multiple places. Integration brings it together.

Simple explanation: It's like collecting all your toys from different rooms into one toy box.

Real-life example: A company integrates sales data from its website, stores, and partners.

School example: A teacher integrates grades from different subjects into one report card.

Home example: You integrate your expenses from different apps into one budget.

Nigerian example: A bank integrates customer data from branches across the country.

Illustration:

Data Sources → Integration → Unified Dataset
   Excel  →          ↓
   CSV    →    [Power Query]   →   Final Table
   Web    →          ↑
   DB     →          ↓

Mini summary: Integration combines data from multiple sources.

Lesson 2: Connecting to Data Sources in Power Query

Definition: You can connect to many data sources: Excel, CSV, Text files, databases, web, and more.

Why important: Power Query works with many different types of data.

Simple explanation: It's like having a universal charger for all your devices.

Real-life example: Connect to a SQL database for sales data.

School example: Connect to a CSV file of student grades.

Home example: Connect to an Excel file of your budget.

Nigerian example: Connect to a web service for exchange rates.

How to do it: Get Data → Choose the source type.

Illustration:

Get Data → From File → From Excel
Get Data → From Database → From SQL Server
Get Data → From Web → From Web Page

Mini summary: Power Query can connect to many data sources.

Lesson 3: Data Source Settings and Credentials

Definition: Some data sources require a username and password (credentials) to access.

Why important: You need to provide the right credentials to connect.

Simple explanation: It's like a password to your email.

Real-life example: Connect to a company database with your username and password.

School example: Connect to a school portal with your login.

Home example: Connect to an online bank account.

Nigerian example: Connect to a government database with a username.

How to do it: In the connection dialog, enter your credentials.

Illustration:

Server: myserver
Database: sales
Username: user1
Password: ********

Mini summary: Provide credentials to access secure data sources.

Lesson 4: Refreshing Data in Power Query

Definition: Refreshing data means running your query again to get the latest data.

Why important: Data changes over time. You need the latest information.

Simple explanation: It's like checking your mailbox again for new letters.

Real-life example: Refresh sales data every day to see new orders.

School example: Refresh grades after a new test.

Home example: Refresh your budget after a new expense.

Nigerian example: Refresh election data after new results come in.

How to do it: Right-click the query → Refresh.

Illustration:

Query Name: Sales
   Right-click → Refresh
   (Data updates with latest information)

Mini summary: Refresh gets the latest data.

Lesson 5: Scheduling Data Refreshes

Definition: Scheduling means setting a specific time for the query to refresh automatically.

Why important: You don't have to remember to refresh. It happens automatically.

Simple explanation: It's like setting an alarm clock to wake you up.

Real-life example: Schedule a refresh every morning at 6 AM.

School example: Schedule a refresh after school hours.

Home example: Schedule a refresh every Sunday evening.

Nigerian example: Schedule a refresh at the end of each month.

How to do it: In Power BI, go to Settings → Scheduled Refresh.

Illustration:

Scheduled Refresh:
   Daily at 6:00 AM
   Daily at 6:00 PM

Mini summary: Schedule refreshes to automate updates.

Lesson 6: ETL – Extract, Transform, Load

Definition: ETL is a process that Extract data, Transform it, and Load it into a final destination.

Why important: ETL is the foundation of data integration.

Simple explanation: It's like cooking: get ingredients (Extract), prepare them (Transform), and serve (Load).

Real-life example: Extract sales data, transform it by cleaning, and load it into a report.

School example: Extract grades, transform by calculating averages, and load into a report card.

Home example: Extract expenses, transform by categorizing, and load into a budget.

Nigerian example: Extract voter data, transform by cleaning, and load into an analysis.

Illustration:

Extract  →  Transform  →  Load
   ↓          ↓            ↓
 Raw        Cleaned     Final
 Data        Data        Table

Mini summary: ETL is Extract, Transform, Load.

Lesson 7: Power Query Dataflows

Definition: Dataflows are a way to share and reuse Power Query transformations in the cloud.

Why important: Dataflows make your work reusable and scalable.

Simple explanation: It's like a shared recipe that everyone can use.

Real-life example: A company creates a dataflow to clean customer data, and all teams can use it.

School example: A teacher creates a dataflow to calculate grades, and other teachers can use it.

Home example: You create a dataflow for your budget, and you can use it on different devices.

Nigerian example: A government agency creates a dataflow for population data.

How to do it: In Power BI, create a Dataflow (Preview).

Illustration:

Dataflow: CleanCustomerData
   Used by: Sales Report, Marketing Report, Finance Report

Mini summary: Dataflows are reusable transformations.

Lesson 8: Handling Data Source Changes

Definition: Data sources can change (e.g., file name changes, columns added). You need to handle these changes.

Why important: If the source changes, your query might break.

Simple explanation: It's like your favorite store moving to a new location – you need to update your directions.

Real-life example: A CSV file is renamed from "Sales_2024.csv" to "Sales_2025.csv".

School example: A grade sheet adds a new subject column.

Home example: You start a new expense category.

Nigerian example: A database adds a new field.

How to fix: Update the data source settings or use parameters.

Illustration:

Old Source: Sales_2024.csv
New Source: Sales_2025.csv
Update in Power Query: Change file path.

Mini summary: Update queries when data sources change.

Lesson 9: Using Parameters for Dynamic Connections

Definition: Parameters can be used to change the data source dynamically (e.g., choose a file by year).

Why important: Makes your query flexible for different inputs.

Simple explanation: It's like a dial you can turn to choose what data to load.

Real-life example: A parameter for "Year" to load sales for that year.

School example: A parameter for "Class" to load grades for that class.

Home example: A parameter for "Month" to load expenses for that month.

Nigerian example: A parameter for "State" to load data for that state.

How to do it: Create a parameter, then use it in the file path or query.

Illustration:

Parameter: Year = 2025
File Path: C:\Data\Sales_[Year].csv

Mini summary: Parameters make data sources dynamic.

Lesson 10: Sharing Queries with Others

Definition: You can share your queries by saving them as .pq files or publishing to Power BI.

Why important: Collaboration makes work faster and better.

Simple explanation: It's like sharing your recipe with a friend so they can cook the same dish.

Real-life example: A team shares a query for cleaning sales data.

School example: Teachers share a query for grading.

Home example: Family members share a budget query.

Nigerian example: Analysts share a query for election data.

How to do it: Export query as .pq file or publish to Power BI.

Illustration:

Export Query → Save as .pq → Share via email

Mini summary: Share queries for collaboration.

Lesson 11: Automating with Power Automate

Definition: Power Automate can trigger Power Query refreshes based on events (e.g., when a new file is added).

Why important: Full automation without manual intervention.

Simple explanation: It's like a robot that does the work for you.

Real-life example: When a new sales file is uploaded to a folder, Power Automate triggers a refresh.

School example: When a teacher uploads grades, the report updates automatically.

Home example: When you add a new expense, your budget updates.

Nigerian example: When new election results are published, the dashboard updates.

How to do it: Use Power Automate to trigger Power BI dataset refresh.

Illustration:

New File → Power Automate → Refresh Query → Updated Report

Mini summary: Power Automate triggers automated refreshes.

Lesson 12: Error Handling in Automated Pipelines

Definition: Automated pipelines need error handling to work smoothly.

Why important: If an error occurs, you want to be notified, not have the pipeline break.

Simple explanation: It's like having a backup plan if something goes wrong.

Real-life example: If the data source is unavailable, send an alert.

School example: If a file is missing, send a notification.

Home example: If a connection fails, send a text message.

Nigerian example: If a database is down, send an email.

How to do it: Use try...otherwise and alerts.

Illustration:

try
   Refresh Query
otherwise
   Send Alert: "Refresh failed"

Mini summary: Handle errors to keep pipelines running.

Lesson 13: Optimizing Refresh Performance

Definition: Large queries can take a long time to refresh. Optimize to make them faster.

Why important: Fast refreshes save time.

Simple explanation: It's like making your car faster with better parts.

Real-life example: A company has millions of rows. They optimize to refresh in minutes.

School example: A teacher has many students. They optimize to get reports quickly.

Home example: You have many expenses. You optimize to get your budget fast.

Nigerian example: A bank has many transactions. They optimize for speed.

Tips: Reduce data early, remove unnecessary columns, use incremental refresh.

Illustration:

Before: 10 minutes
After: 2 minutes

Mini summary: Optimize refreshes for speed.

Lesson 14: Incremental Refresh for Large Datasets

Definition: Incremental refresh loads only new or changed data instead of reloading everything.

Why important: Saves time and resources for large datasets.

Simple explanation: Instead of reading the whole book again, you only read the new pages.

Real-life example: A company with 5 years of sales data only loads the last 3 months.

School example: A teacher only loads the latest test scores.

Home example: You only load this month's expenses.

Nigerian example: A bank only loads transactions from the last 7 days.

How to do it: In Power BI, set up incremental refresh policies.

Illustration:

Incremental Refresh:
   Load last 3 months
   Refresh daily

Mini summary: Incremental refresh loads only new data.

Lesson 15: Building an Automated Data Pipeline

Definition: An automated data pipeline is a complete system that extracts, transforms, and loads data automatically.

Why important: A pipeline runs without manual intervention, saving time and ensuring consistency.

Simple explanation: It's like an assembly line in a factory.

Real-life example: Daily sales pipeline: extract from database, transform, load to dashboard.

School example: Weekly grade pipeline: extract from grade book, transform, load to report card.

Home example: Monthly budget pipeline: extract from bank, transform, load to budget tracker.

Nigerian example: Election results pipeline: extract from polling units, transform, load to national dashboard.

Steps: Plan, build, test, deploy, monitor.

Illustration:

Plan → Build → Test → Deploy → Monitor

Mini summary: A pipeline automates the entire ETL process.

📖 Key Vocabulary (with simple definitions)

  • Data Integration: Combining data from different sources.
  • Refresh: Updating data with the latest information.
  • Schedule: Setting a time for automatic updates.
  • ETL: Extract, Transform, Load.
  • Dataflow: A reusable set of transformations.
  • Parameter: A variable that can be changed.
  • Incremental Refresh: Loading only new data.
  • Pipeline: A series of automated steps.

🧠 Important Concepts

  • Data integration brings data together.
  • ETL is the foundation of integration.
  • Automation saves time and reduces errors.
  • Dataflows make transformations reusable.
  • Incremental refresh improves performance.

🔢 Step-by-Step Explanations

How to Set Up Scheduled Refresh:

  1. Publish your dataset to Power BI.
  2. Go to the dataset in Power BI Service.
  3. Click Settings.
  4. Expand "Scheduled Refresh".
  5. Set the time and frequency.
  6. Save.

How to Create a Parameter for Dynamic File Path:

  1. Go to Home → Manage Parameters → New.
  2. Name it "FilePath".
  3. Set type to Text.
  4. Set value to "C:\Data\Sales.csv".
  5. In your query, use = Parameter & "" to build the path.

🌍 Real-life Examples

  • Retail: Integrate sales data from stores and online, refresh daily.
  • Healthcare: Integrate patient records from hospitals, refresh weekly.
  • Finance: Integrate transaction data from branches, refresh hourly.

🇳🇬 Nigerian Examples

  • Election: Integrate results from all polling units, refresh as results come in.
  • Agriculture: Integrate crop data from all states, refresh monthly.
  • Telecom: Integrate call records from all regions, refresh daily.

🎈 Fun Examples Children Can Relate To

  • Toys: Integrate toy inventory from different stores, refresh weekly.
  • Candy: Integrate candy sales from different machines, refresh daily.
  • Games: Integrate game scores from different players, refresh after each game.

🏠 Everyday Examples

  • Budget: Integrate expenses from your bank and cash, refresh weekly.
  • Chores: Integrate chore data from family members, refresh daily.
  • School: Integrate grades from different teachers, refresh after tests.

👩‍🏫 Teacher Notes

  • Emphasize the importance of automation in real-world data analysis.
  • Demonstrate scheduling and dataflows in Power BI.
  • Encourage students to build a complete automated pipeline.

👨‍👩‍👦 Parent Tips

  • Help your child set up a simple automation (e.g., a budget that updates weekly).
  • Discuss how automation saves time in daily life.

💡 Interesting Facts

  • Many companies spend 80% of their time on data integration and only 20% on analysis.
  • Power Query can refresh data from over 100 different sources.
  • Automated pipelines reduce errors significantly.

❓ Did You Know?

Did you know that you can use Power Query to connect to data from Facebook, Google Analytics, and many other web services? It's like a super connector!

🔔 Remember This

  • Integration combines data from multiple sources.
  • ETL is Extract, Transform, Load.
  • Automation saves time and reduces errors.
  • Dataflows make transformations reusable.
  • Incremental refresh improves performance.

⚠️ Common Mistakes

  • Not setting up scheduled refresh – data becomes outdated.
  • Forgetting to handle data source changes – queries break.
  • Not optimizing performance – refreshes take too long.
  • Not using parameters – queries are not flexible.

✅ Best Practices

  • Set up scheduled refresh for important reports.
  • Use parameters for dynamic data sources.
  • Implement incremental refresh for large datasets.
  • Use dataflows for reusable transformations.
  • Monitor refresh failures and fix them.

📊 ASCII Illustrations

ETL Process

   Extract        Transform         Load
      ↓              ↓               ↓
   Raw Data  →  Cleaned Data  →  Final Report
      |              |               |
   Sales DB    Remove Errors    Dashboard
   Excel       Merge Tables     Power BI
   Web         Calculate        Excel

Automated Data Pipeline

   Data Sources (Excel, CSV, DB)
           |
           V
    Power Query (Transform)
           |
           V
    Load to Power BI
           |
           V
    Scheduled Refresh (Daily)
           |
           V
    Updated Dashboard

📋 Comparison Tables

Manual vs Automated Process

FeatureManualAutomated
TimeHighLow
Error rateHighLow
ConsistencyVariesHigh
ScalabilityLowHigh

Full Refresh vs Incremental Refresh

FeatureFull RefreshIncremental Refresh
Data loadedAll dataOnly new data
TimeLongShort
Resource usageHighLow
Best forSmall datasetsLarge datasets

📝 End-of-Module Summary

Congratulations! You have completed Module Twelve on Data Integration and Automation. You learned:

  • What data integration and ETL mean.
  • How to connect to different data sources.
  • How to set up scheduled refresh.
  • How to use dataflows and parameters.
  • How to optimize performance with incremental refresh.
  • How to build a complete automated data pipeline.

You can now build systems that automatically bring in fresh data, transform it, and deliver insights without manual effort. This is a superpower in the world of data analysis!

❓ Frequently Asked Questions (10)

  1. What is data integration? – Combining data from different sources.
  2. What is ETL? – Extract, Transform, Load.
  3. How do I refresh data? – Right-click query → Refresh.
  4. How do I schedule refresh? – In Power BI Settings.
  5. What is a dataflow? – A reusable transformation.
  6. What is a parameter? – A variable that can be changed.
  7. What is incremental refresh? – Loading only new data.
  8. How do I handle data source changes? – Update settings or use parameters.
  9. What is a pipeline? – A series of automated steps.
  10. How do I optimize performance? – Reduce data early, use incremental refresh.

📝 Review Questions (15)

  1. What is data integration?
  2. What does ETL stand for?
  3. How do you refresh a query?
  4. How do you schedule a refresh?
  5. What is a dataflow?
  6. What is a parameter?
  7. What is incremental refresh?
  8. How do you handle data source changes?
  9. What is a pipeline?
  10. How do you optimize refresh performance?
  11. What is the purpose of credentials?
  12. How do you share a query?
  13. What is Power Automate used for?
  14. Why is automation important?
  15. Name three data sources Power Query can connect to.

✍️ Fill-in-the-Blank Exercises

  1. ______ combines data from different sources.
  2. ETL stands for Extract, ______, Load.
  3. ______ updates data with the latest information.
  4. A ______ is a reusable transformation.
  5. ______ refresh loads only new data.

✅ True or False Exercises

  1. Data integration is only for Excel files. (False)
  2. ETL is a one-time process. (False)
  3. You can schedule refresh in Power BI. (True)
  4. Dataflows are not reusable. (False)
  5. Incremental refresh loads all data. (False)

🔘 Multiple Choice Questions (15 with answers)

  1. What does ETL stand for?
    a) Extract, Transform, Load b) Edit, Transform, Load c) Extract, Table, Load d) Edit, Table, Load
    Answer: a
  2. How do you refresh a query?
    a) Right-click → Refresh b) Double-click c) Delete d) Rename
    Answer: a
  3. What is a dataflow?
    a) A table b) A reusable transformation c) A column d) A chart
    Answer: b
  4. What is a parameter?
    a) A fixed value b) A variable c) A table d) A column
    Answer: b
  5. What is incremental refresh?
    a) Loading all data b) Loading only new data c) Loading no data d) Deleting data
    Answer: b
  6. How do you schedule refresh in Power BI?
    a) Dataset Settings b) Report Settings c) Dashboard Settings d) Workspace Settings
    Answer: a
  7. Which is NOT a data source?
    a) Excel b) CSV c) SQL d) PowerPoint
    Answer: d
  8. What is a pipeline?
    a) A single step b) A series of steps c) A table d) A column
    Answer: b
  9. What is the purpose of credentials?
    a) To access secure data b) To delete data c) To hide data d) To sort data
    Answer: a
  10. What does Power Automate do?
    a) Creates charts b) Triggers workflows c) Deletes data d) Formats text
    Answer: b
  11. Why use incremental refresh?
    a) To save time b) To delete data c) To hide data d) To format data
    Answer: a
  12. What is a data source?
    a) A place where data comes from b) A chart c) A report d) A dashboard
    Answer: a
  13. How do you share a query?
    a) Save as .pq b) Delete c) Rename d) Hide
    Answer: a
  14. What is the first step in ETL?
    a) Extract b) Transform c) Load d) Refresh
    Answer: a
  15. What is the last step in ETL?
    a) Extract b) Transform c) Load d) Refresh
    Answer: c

🔗 Matching Exercises

Match the term to its description:

TermDescription
1. ETLA. Reusable transformation
2. DataflowB. Extract, Transform, Load
3. ParameterC. Loading only new data
4. Incremental RefreshD. Variable that can be changed

Answers: 1-B, 2-A, 3-D, 4-C

✍️ Short Answer Questions

  1. What is data integration?
  2. Explain ETL with an example.
  3. What is the purpose of scheduled refresh?
  4. What is the advantage of incremental refresh?
  5. How do you handle data source changes?

📖 Scenario-based Exercises

Scenario 1: You have a daily sales report that needs to be updated every morning at 8 AM. You have a sales database that updates overnight. How would you set this up in Power Query and Power BI?

Scenario 2: Your data source (a CSV file) changes name every month (e.g., Sales_Jan.csv, Sales_Feb.csv). How would you use a parameter to handle this?

👥 Group Activity

In groups, design an automated data pipeline for a scenario of your choice (e.g., school grades, store sales). Include data sources, transformation steps, refresh schedule, and handling of changes.

🧑‍🎓 Individual Activity

Set up a simple automated pipeline with a CSV file that updates daily. Use Power Query to clean and transform the data, and schedule refresh in Power BI. Document your setup.

💬 Classroom Discussion Questions

  • Why is automation important in data analysis?
  • What challenges might you face with automated pipelines?
  • How can you ensure your pipeline is reliable?

🛠️ Mini Project

Project: Automated Sales Dashboard

Build a complete automated sales dashboard. Use at least two data sources (e.g., Excel and CSV). Clean and merge the data. Set up scheduled refresh. Add a parameter for year. Present the dashboard to the class.

📋 Practical Assignment

Download a dataset that updates daily (e.g., COVID-19 data). Build a pipeline that cleans the data, transforms it, and loads it into Power BI. Set up scheduled refresh. Write a report on your pipeline.

🏆 Challenge Exercise

Create a parameterized dataflow that can connect to different databases based on a parameter (e.g., database name). Use this dataflow in a pipeline. Demonstrate how changing the parameter updates the entire pipeline.

📝 Quiz Answers

Fill-in-the-Blank: 1. Integration, 2. Transform, 3. Refresh, 4. dataflow, 5. Incremental

True/False: 1-F, 2-F, 3-T, 4-F, 5-F

Matching: 1-B, 2-A, 3-D, 4-C

🔑 Key Takeaways

  • Data integration brings data together from different sources.
  • ETL is the foundation of data integration.
  • Automation saves time and reduces errors.
  • Dataflows and parameters make queries reusable.
  • Incremental refresh improves performance.
  • Always monitor your automated pipelines.

📖 Preparation for the Next Module

In Module Thirteen, we will learn about Data Modeling and Relationships – how to build a data model with relationships between tables. This is the foundation of creating amazing reports and dashboards. Get ready to become a Data Modeler!

Before the next class, practice setting up a scheduled refresh for a simple dataset. Try using a parameter for the file path.


© 2025 Certified Power Query for Data Analysis Expert – Module Twelve

14

Module Thirteen

Module 13 · Power Query for Data Analysis Expert

🧱 Module Thirteen: Data Modeling and Relationships

Hello, young data explorer! Welcome to Module Thirteen. In this module, we will learn how to build a data model and create relationships between tables. Think of this as building the skeleton of your report. Just like your skeleton holds your body together, a data model holds your data together. By the end of this module, you will be able to connect different tables, set up relationships, and build a solid foundation for amazing reports and dashboards.

🎯 Learning Objectives

  • Understand what a data model is.
  • Learn what relationships are and why they matter.
  • Learn about primary and foreign keys.
  • Learn about different relationship types: one-to-one, one-to-many, many-to-many.
  • Learn how to create relationships in Power BI.
  • Learn about cardinality and cross-filter direction.
  • Understand how relationships help create accurate reports.
  • Learn about star schemas and snowflake schemas.
  • Learn how to handle inactive relationships.
  • Build a complete data model from multiple tables.

📖 Warm-up Story: The Puzzle of the Three Tables

Chidi has three tables: one with customer names, one with orders, and one with products. He wants to see which customer bought which product. He needs to connect these tables. He uses the customer ID to link customers to orders, and the product ID to link orders to products. Now he can see the full picture – who bought what! That's exactly what data modeling does – it connects tables to tell a complete story.

📚 Main Lessons (15 Lessons)

Lesson 1: What is a Data Model?

Definition: A data model is a framework that organizes and defines how different tables are connected to each other.

Why important: A good data model makes your reports accurate, fast, and easy to understand.

Simple explanation: It's like a map that shows how different parts of your data fit together.

Real-life example: A company has customer, order, and product tables. The data model connects them.

School example: A teacher has student, grade, and subject tables. The data model connects them.

Home example: You have family member, chore, and day tables. The data model connects them.

Nigerian example: A bank has customer, account, and transaction tables. The data model connects them.

Illustration:

Data Model Diagram:
+----------+       +--------+       +----------+
| Customers|       | Orders |       | Products |
+----------+       +--------+       +----------+
| CustID   |──────▶| CustID |       | ProdID   |
| Name     |       | OrderID|──────▶| ProdID   |
| City     |       | ProdID |       | Name     |
+----------+       | Amount |       | Price    |
                   +--------+       +----------+

Mini summary: A data model connects tables.

Lesson 2: What is a Relationship?

Definition: A relationship is a connection between two tables based on a common column.

Why important: Relationships allow you to combine data from different tables to answer questions.

Simple explanation: It's like a bridge that connects two islands.

Real-life example: Customers table and Orders table are connected by Customer ID.

School example: Students table and Grades table are connected by Student ID.

Home example: Family Members table and Chores table are connected by Member ID.

Nigerian example: Citizens table and Voting table are connected by Voter ID.

Illustration:

+----------+          +----------+
| Customers|          | Orders   |
+----------+          +----------+
| CustID   |───(Relationship)───▶| CustID   |
| Name     |          | OrderID  |
+----------+          +----------+

Mini summary: Relationships connect tables.

Lesson 3: Primary Key and Foreign Key

Definition: A primary key is a column that uniquely identifies each row in a table. A foreign key is a column that links to a primary key in another table.

Why important: Keys are the building blocks of relationships.

Simple explanation: A primary key is like a student's ID number – unique to them. A foreign key is like the same ID number used in another list to refer to that student.

Real-life example: Customer ID in Customers table is a primary key. Customer ID in Orders table is a foreign key.

School example: Student ID in Students table is a primary key. Student ID in Grades table is a foreign key.

Home example: Member ID in Family table is a primary key. Member ID in Chores table is a foreign key.

Nigerian example: NIN in Citizens table is a primary key. NIN in Voting table is a foreign key.

Illustration:

+----------+          +----------+
| Customers|          | Orders   |
+----------+          +----------+
| CustID (PK)│◀────────| CustID (FK)│
| Name     |          | OrderID   |
+----------+          +----------+

Mini summary: Primary key uniquely identifies rows. Foreign key links to another table.

Lesson 4: One-to-One Relationship

Definition: A one-to-one relationship means that one row in Table A is linked to exactly one row in Table B.

Why important: Used when you want to split a table into two for security or organization.

Simple explanation: Each person has exactly one birth certificate.

Real-life example: Employee table and Employee Details table – each employee has one detail record.

School example: Student table and Student Medical Record – each student has one medical record.

Home example: Family Member table and Passport table – each member has one passport.

Nigerian example: Citizen table and NIN table – each citizen has one NIN.

Illustration:

+----------+          +----------+
| Employee |          | Details  |
+----------+          +----------+
| EmpID (PK)│──────────│ EmpID (FK)│
| Name     |          | Address  |
+----------+          +----------+
Each employee has exactly one detail record.

Mini summary: One-to-one: each row matches exactly one row in the other table.

Lesson 5: One-to-Many Relationship

Definition: A one-to-many relationship means that one row in Table A can link to many rows in Table B.

Why important: This is the most common type of relationship.

Simple explanation: One customer can have many orders.

Real-life example: One customer can have many orders.

School example: One teacher can teach many students.

Home example: One parent can have many children.

Nigerian example: One state can have many LGAs.

Illustration:

+----------+          +----------+
| Customers|          | Orders   |
+----------+          +----------+
| CustID (PK)│──────────│ CustID (FK)│
| Name     |          | OrderID   |
+----------+          +----------+
One customer can have many orders.

Mini summary: One-to-many: one row links to many rows in the other table.

Lesson 6: Many-to-Many Relationship

Definition: A many-to-many relationship means that many rows in Table A can link to many rows in Table B.

Why important: Need a junction table to connect them.

Simple explanation: Many students can take many subjects.

Real-life example: Students and Subjects – a student takes many subjects, and a subject is taken by many students.

School example: Students and Clubs – a student can join many clubs, a club can have many students.

Home example: Family Members and Hobbies – a member can have many hobbies, a hobby can be shared by many members.

Nigerian example: Citizens and Services – a citizen can use many services, a service can be used by many citizens.

How to handle: Create a junction table (e.g., Student_Subject) with the keys from both tables.

Illustration:

+----------+       +------------------+       +----------+
| Students |       | Student_Subject  |       | Subjects |
+----------+       +------------------+       +----------+
| StuID (PK)│──────▶| StuID (FK)       |◀──────| SubID (PK)│
| Name     |       | SubID (FK)       |       | Name     |
+----------+       +------------------+       +----------+
Many students, many subjects.

Mini summary: Many-to-many: many rows link to many rows, requiring a junction table.

Lesson 7: Creating Relationships in Power BI

Definition: In Power BI, you can create relationships between tables visually.

Why important: Power BI uses these relationships to build reports.

Simple explanation: You drag and drop to connect tables.

Real-life example: You have a Customers table and an Orders table. You drag CustID from Customers to CustID in Orders.

School example: You have Students and Grades. You drag StudentID from Students to StudentID in Grades.

Home example: You have Members and Chores. You drag MemberID from Members to MemberID in Chores.

Nigerian example: You have States and LGAs. You drag StateID from States to StateID in LGAs.

How to do it: In Power BI, go to Model View, drag a field from one table to another.

Illustration:

Model View:
   Drag CustID from Customers to CustID in Orders.
   A line appears between the tables.

Mini summary: Drag fields to create relationships in Power BI.

Lesson 8: Cardinality – The Direction of Relationships

Definition: Cardinality defines the type of relationship (one-to-one, one-to-many, many-to-many).

Why important: It tells Power BI how to use the relationship.

Simple explanation: It's like a traffic sign telling cars which way to go.

Real-life example: One customer to many orders = one-to-many.

School example: One teacher to many students = one-to-many.

Home example: One parent to many children = one-to-many.

Nigerian example: One state to many LGAs = one-to-many.

How to set: In the relationship dialog, choose the cardinality.

Illustration:

Cardinality Options:
   One-to-One: (1:1)
   One-to-Many: (1:*)
   Many-to-One: (*:1)
   Many-to-Many: (*:*)

Mini summary: Cardinality defines the relationship type.

Lesson 9: Cross-Filter Direction

Definition: Cross-filter direction tells Power BI how filters flow between tables.

Why important: It determines how filtering affects other tables.

Simple explanation: It's like a one-way or two-way street.

Real-life example: If you filter customers, the orders table should be filtered too.

School example: If you filter a subject, the grades for that subject appear.

Home example: If you filter a family member, their chores appear.

Nigerian example: If you filter a state, its LGAs appear.

How to set: In the relationship dialog, choose single or both directions.

Illustration:

Cross-Filter Direction:
   Single: Filter flows one way.
   Both: Filter flows both ways.

Mini summary: Cross-filter direction controls how filters propagate.

Lesson 10: Star Schema – The Ideal Data Model

Definition: A star schema is a data model with one central fact table and many dimension tables.

Why important: Star schemas are fast and easy to understand.

Simple explanation: The fact table is like the sun in the center, and dimension tables are like planets orbiting around it.

Real-life example: Fact table: Sales. Dimension tables: Products, Customers, Time.

School example: Fact table: Grades. Dimension tables: Students, Subjects, Teachers.

Home example: Fact table: Expenses. Dimension tables: Categories, Members, Months.

Nigerian example: Fact table: Votes. Dimension tables: Candidates, States, Parties.

Illustration:

        +----------+
        | Products |
        +----------+
             |
+----------+----------+----------+
| Customers|──│ Sales   │──│ Time   |
+----------+----------+----------+
             |
        +----------+
        | Regions  |
        +----------+

Mini summary: Star schema: one fact table, many dimension tables.

Lesson 11: Fact Tables and Dimension Tables

Definition: Fact tables contain numerical data (sales, scores). Dimension tables contain descriptive data (names, categories).

Why important: This is the foundation of a star schema.

Simple explanation: Fact tables answer "how much?" Dimension tables answer "who? what? where?"

Real-life example: Fact: Sales Amount. Dimension: Product Name, Customer Name, Date.

School example: Fact: Score. Dimension: Student Name, Subject Name, Teacher Name.

Home example: Fact: Amount Spent. Dimension: Category, Member, Day.

Nigerian example: Fact: Vote Count. Dimension: Party, State, Candidate.

Illustration:

Fact Table: Sales (Amount, Qty)
Dimension Tables: Product (Name), Customer (Name), Date (Year, Month)

Mini summary: Fact tables have numbers, dimension tables have descriptions.

Lesson 12: Snowflake Schema

Definition: A snowflake schema is a star schema where dimension tables are further normalized into sub-dimensions.

Why important: Used when dimensions are very large.

Simple explanation: It's like a star schema with extra branches.

Real-life example: Product dimension is split into Product, Brand, and Category.

School example: Student dimension is split into Student, Class, and Grade.

Home example: Expense dimension is split into Expense, Category, and Sub-category.

Nigerian example: State dimension is split into State, Region, and Zone.

Illustration:

        +----------+
        | Products |
        +----------+
             |
        +----------+          +----------+
        | Brands   |──────────| Category |
        +----------+          +----------+

Mini summary: Snowflake schema has normalized dimensions.

Lesson 13: Inactive Relationships

Definition: Inactive relationships are relationships that are not used by default.

Why important: Sometimes you need to switch relationships for different reports.

Simple explanation: It's like having a backup bridge you only use sometimes.

Real-life example: You have relationships between OrderDate and DeliveryDate. You can use one at a time.

School example: You have relationships between ExamDate and AssignmentDate.

Home example: You have relationships between PurchaseDate and UseDate.

Nigerian example: You have relationships between RegistrationDate and VotingDate.

How to use: Use DAX functions like USERELATIONSHIP to activate.

Illustration:

Active: Relationship on OrderDate
Inactive: Relationship on DeliveryDate
Use USERELATIONSHIP to switch.

Mini summary: Inactive relationships can be activated when needed.

Lesson 14: Handling Many-to-Many Relationships

Definition: Many-to-many relationships require a junction table.

Why important: They are common and need special handling.

Simple explanation: You need a bridge table to connect them.

Real-life example: Students and Subjects – junction table StudentSubject.

School example: Students and Clubs – junction table StudentClub.

Home example: Members and Hobbies – junction table MemberHobby.

Nigerian example: Citizens and Services – junction table CitizenService.

How to do it: Create a junction table with the primary keys of both tables.

Illustration:

Students (StuID) ─── StudentSubject (StuID, SubID) ─── Subjects (SubID)

Mini summary: Use a junction table for many-to-many relationships.

Lesson 15: Best Practices for Data Modeling

Definition: Tips for building a solid data model.

Why important: A good model leads to accurate and fast reports.

Simple explanation: It's like building a strong foundation for a house.

  • Use a star schema (fact and dimension tables).
  • Use clear and descriptive column names.
  • Ensure primary keys are unique.
  • Define relationships correctly.
  • Hide unnecessary columns.
  • Document your model.

Illustration:

1. Identify Fact and Dimension tables.
2. Create relationships using keys.
3. Set cardinality and cross-filter direction.
4. Test with sample reports.

Mini summary: Follow best practices for a robust data model.

📖 Key Vocabulary (with simple definitions)

  • Data Model: A framework that organizes tables and their relationships.
  • Relationship: A connection between two tables.
  • Primary Key: A unique identifier for a row.
  • Foreign Key: A field that links to a primary key in another table.
  • One-to-One: Each row matches exactly one row in the other table.
  • One-to-Many: One row matches many rows in the other table.
  • Many-to-Many: Many rows match many rows in the other table.
  • Star Schema: A model with one fact table and many dimension tables.
  • Fact Table: Contains numerical data.
  • Dimension Table: Contains descriptive data.

🧠 Important Concepts

  • Relationships connect tables to enable combined analysis.
  • Primary and foreign keys are the building blocks of relationships.
  • Star schemas are the preferred data model for reporting.
  • Cardinality defines how rows relate between tables.
  • Cross-filter direction controls how filters propagate.

🔢 Step-by-Step Explanations

How to Create a Relationship in Power BI:

  1. Open Power BI and load your tables.
  2. Go to Model View (left side).
  3. Find the two tables you want to connect.
  4. Drag the primary key from one table to the foreign key in the other.
  5. A line appears. Double-click it to set cardinality and cross-filter direction.
  6. Click OK.

How to Build a Star Schema:

  1. Identify your fact table (the table with numbers).
  2. Identify your dimension tables (the tables with descriptions).
  3. Create relationships between the fact table and each dimension table.
  4. Ensure the fact table is in the center and dimensions are around it.

🌍 Real-life Examples

  • Retail: Sales fact table, dimension tables: Products, Customers, Stores, Time.
  • Healthcare: Patient visits fact, dimension tables: Patients, Doctors, Departments.
  • Finance: Transactions fact, dimension tables: Accounts, Customers, Branches.

🇳🇬 Nigerian Examples

  • Election: Votes fact, dimension tables: Parties, States, LGAs, Candidates.
  • Agriculture: Crop yield fact, dimension tables: Crops, States, Farmers.
  • Telecom: Call records fact, dimension tables: Customers, Networks, Regions.

🎈 Fun Examples Children Can Relate To

  • Toys: Sales fact, dimension tables: Toys, Stores, Kids.
  • Candy: Sales fact, dimension tables: Candy types, Shops, Seasons.
  • Games: Scores fact, dimension tables: Players, Games, Levels.

🏠 Everyday Examples

  • Budget: Expenses fact, dimension tables: Categories, Months, Members.
  • Chores: Chores completed fact, dimension tables: Members, Days, Tasks.
  • School: Grades fact, dimension tables: Students, Subjects, Teachers.

👩‍🏫 Teacher Notes

  • Use building block analogies to explain keys and relationships.
  • Emphasize the importance of a good data model for accurate reports.
  • Practice building star schemas with different datasets.

👨‍👩‍👦 Parent Tips

  • Help your child draw a data model on paper to visualize connections.
  • Discuss how different tables (like a phonebook and a list of birthdays) can be connected.

💡 Interesting Facts

  • Data modeling is considered one of the most important skills for a data analyst.
  • Power BI can automatically detect relationships in some cases.
  • Star schemas were invented by Ralph Kimball in the 1990s.

❓ Did You Know?

Did you know that a well-designed data model can make your reports 10 times faster than a poorly designed one? That's why data modeling is so important!

🔔 Remember This

  • Relationships connect tables.
  • Primary keys uniquely identify rows.
  • Foreign keys link to primary keys.
  • Star schemas are best for reporting.
  • Fact tables have numbers, dimension tables have descriptions.

⚠️ Common Mistakes

  • Not defining primary keys – causes duplicates and confusion.
  • Using wrong cardinality – leads to incorrect results.
  • Creating circular relationships – causes errors.
  • Not using a star schema – makes reports slow and complex.

✅ Best Practices

  • Always use a star schema if possible.
  • Ensure primary keys are unique and not null.
  • Use clear and descriptive names for tables and columns.
  • Set cardinality and cross-filter direction correctly.
  • Document your data model.

📊 ASCII Illustrations

Star Schema

        +----------+
        | Products |
        +----------+
             |
+----------+----------+----------+
| Customers|──│ Sales   │──│ Time   |
+----------+----------+----------+
             |
        +----------+
        | Stores   |
        +----------+

Primary Key and Foreign Key

+----------+          +----------+
| Customers|          | Orders   |
+----------+          +----------+
| CustID (PK)│──────────│ CustID (FK)│
| Name     |          | OrderID   |
+----------+          +----------+

📋 Comparison Tables

Fact vs Dimension Table

FeatureFact TableDimension Table
Data typeNumericalDescriptive
SizeLarge (many rows)Small (few rows)
ExampleSales amountProduct name
PurposeMeasure performanceProvide context

Star vs Snowflake Schema

FeatureStar SchemaSnowflake Schema
ComplexitySimpleMore complex
PerformanceFasterSlower
NormalizationDenormalizedNormalized
Use whenMost casesVery large dimensions

📝 End-of-Module Summary

Congratulations! You have completed Module Thirteen on Data Modeling and Relationships. You learned:

  • What a data model is and why it's important.
  • How to create relationships between tables.
  • About primary and foreign keys.
  • The three types of relationships: one-to-one, one-to-many, many-to-many.
  • How to build a star schema with fact and dimension tables.
  • How to handle many-to-many relationships with junction tables.
  • Best practices for building a solid data model.

You are now ready to build robust data models that will make your reports accurate, fast, and easy to understand!

❓ Frequently Asked Questions (10)

  1. What is a data model? – A framework that organizes tables and relationships.
  2. What is a relationship? – A connection between two tables.
  3. What is a primary key? – A unique identifier for a row.
  4. What is a foreign key? – A field that links to a primary key.
  5. What is one-to-many relationship? – One row links to many rows.
  6. What is a star schema? – A model with a fact table and dimension tables.
  7. What is a fact table? – Contains numerical data.
  8. What is a dimension table? – Contains descriptive data.
  9. How do you handle many-to-many relationships? – Use a junction table.
  10. Why is data modeling important? – It ensures accurate and fast reports.

📝 Review Questions (15)

  1. What is a data model?
  2. What is a relationship?
  3. What is a primary key?
  4. What is a foreign key?
  5. What is a one-to-one relationship?
  6. What is a one-to-many relationship?
  7. What is a many-to-many relationship?
  8. What is a star schema?
  9. What is a fact table?
  10. What is a dimension table?
  11. How do you handle many-to-many relationships?
  12. What is cardinality?
  13. What is cross-filter direction?
  14. What is a snowflake schema?
  15. Why is data modeling important?

✍️ Fill-in-the-Blank Exercises

  1. A ______ key uniquely identifies a row.
  2. A ______ key links to a primary key.
  3. One customer to many orders is a ______ relationship.
  4. A ______ schema has a central fact table and dimension tables.
  5. ______ tables contain descriptive data.

✅ True or False Exercises

  1. A primary key can have duplicate values. (False)
  2. A foreign key links to a primary key. (True)
  3. One-to-many is the most common relationship. (True)
  4. A star schema has many fact tables. (False)
  5. Dimension tables contain numerical data. (False)

🔘 Multiple Choice Questions (15 with answers)

  1. What uniquely identifies a row in a table?
    a) Foreign Key b) Primary Key c) Foreign Table d) Primary Table
    Answer: b
  2. What links to a primary key in another table?
    a) Foreign Key b) Primary Key c) Foreign Table d) Primary Table
    Answer: a
  3. One customer to many orders is which relationship?
    a) One-to-One b) One-to-Many c) Many-to-One d) Many-to-Many
    Answer: b
  4. What is a star schema?
    a) A model with one fact and many dimensions b) A model with many facts and one dimension c) A model with no relationships d) A model with only tables
    Answer: a
  5. What does a fact table contain?
    a) Descriptive data b) Numerical data c) Text data d) Both a and b
    Answer: b
  6. What does a dimension table contain?
    a) Descriptive data b) Numerical data c) Text data d) Both a and b
    Answer: a
  7. How do you handle many-to-many relationships?
    a) Direct relationship b) Junction table c) Merge d) Append
    Answer: b
  8. What is cardinality?
    a) The number of tables b) The type of relationship c) The number of rows d) The number of columns
    Answer: b
  9. What is cross-filter direction?
    a) How filters flow b) How data is stored c) How tables are named d) How columns are sorted
    Answer: a
  10. What is a snowflake schema?
    a) A star schema with normalized dimensions b) A model with no dimensions c) A model with only fact tables d) A model with only relationships
    Answer: a
  11. Which is NOT a relationship type?
    a) One-to-One b) One-to-Many c) Many-to-Many d) One-to-Zero
    Answer: d
  12. What is the first step in building a star schema?
    a) Create relationships b) Identify fact and dimension tables c) Load data d) Create reports
    Answer: b
  13. What is the purpose of a data model?
    a) To organize data b) To hide data c) To delete data d) To sort data
    Answer: a
  14. What is a junction table?
    a) A table that connects two tables b) A table with no relationships c) A fact table d) A dimension table
    Answer: a
  15. Why is data modeling important?
    a) For accurate and fast reports b) For slow reports c) For hiding data d) For deleting data
    Answer: a

🔗 Matching Exercises

Match the term to its description:

TermDescription
1. Primary KeyA. Links to a primary key
2. Foreign KeyB. Unique identifier
3. One-to-ManyC. One row links to many
4. Star SchemaD. Fact and dimension tables

Answers: 1-B, 2-A, 3-C, 4-D

✍️ Short Answer Questions

  1. What is the difference between a primary key and a foreign key?
  2. Explain the three types of relationships.
  3. What is a star schema and why is it used?
  4. How do you handle many-to-many relationships?
  5. Why is a good data model important?

📖 Scenario-based Exercises

Scenario 1: You have tables: Students (StudentID, Name), Grades (StudentID, Subject, Score). What type of relationship is this? How would you connect them?

Scenario 2: You have tables: Products (ProdID, Name), Orders (OrderID, ProdID, Qty), Customers (CustID, Name). Design a star schema with these tables.

👥 Group Activity

In groups, choose a scenario (e.g., school data, store data). Design a data model with at least three tables. Draw it on paper and present it to the class. Identify fact and dimension tables, primary and foreign keys, and relationship types.

🧑‍🎓 Individual Activity

Load two or three related tables into Power BI. Create relationships between them. Then create a simple report that uses all tables. Document your model.

💬 Classroom Discussion Questions

  • Why is a star schema better than a flat table?
  • What challenges do you face when building a data model?
  • How do relationships affect report accuracy?

🛠️ Mini Project

Project: Build a Sales Data Model

You have four tables: Sales (OrderID, CustomerID, ProductID, DateID, Amount), Customers (CustomerID, Name, City), Products (ProductID, Name, Category), Dates (DateID, Year, Month, Day). Build a star schema in Power BI. Create relationships and set cardinality. Then create a simple sales report.

📋 Practical Assignment

Download a dataset with multiple related tables. Build a data model in Power BI. Create at least three relationships. Document your model with a diagram and explanation of keys and cardinality.

🏆 Challenge Exercise

You have a dataset with sales data that has a many-to-many relationship between products and customers (a product can be bought by many customers, a customer can buy many products). Use a junction table to resolve this relationship. Build a report that shows which customer buys which product.

📝 Quiz Answers

Fill-in-the-Blank: 1. Primary, 2. Foreign, 3. one-to-many, 4. star, 5. Dimension

True/False: 1-F, 2-T, 3-T, 4-F, 5-F

Matching: 1-B, 2-A, 3-C, 4-D

🔑 Key Takeaways

  • A data model organizes tables and relationships.
  • Relationships connect tables using keys.
  • Star schemas are the best for reporting.
  • Fact tables have numbers, dimension tables have descriptions.
  • Always document your data model.

📖 Preparation for the Next Module

In Module Fourteen, we will learn about DAX (Data Analysis Expressions) – the language that creates powerful calculations in Power BI. You will learn how to write formulas that make your reports even more intelligent. Get ready to become a DAX wizard!

Before the next class, practice building a data model with at least three tables and one relationship.


© 2025 Certified Power Query for Data Analysis Expert – Module Thirteen

15

Module Fourteen

Module 14 · Power Query for Data Analysis Expert

🧮 Module Fourteen: Introduction to DAX

Hello, young data explorer! Welcome to Module Fourteen. In this module, we will learn about DAX – Data Analysis Expressions. DAX is a language that helps us create powerful calculations in Power BI. Think of DAX as a magic wand that can answer any question you have about your data. You can create new columns, make calculations, and build advanced measures. By the end of this module, you will be able to write your own DAX formulas and make your reports smarter!

🎯 Learning Objectives

  • Understand what DAX is and why it's important.
  • Learn the difference between calculated columns and measures.
  • Learn about basic DAX functions: SUM, AVERAGE, COUNT.
  • Learn about CALCULATE and its power.
  • Learn about time intelligence functions (TOTALYTD, SAMEPERIODLASTYEAR).
  • Learn about FILTER and row context.
  • Understand the concept of context in DAX.
  • Learn about common DAX patterns.
  • Write your own DAX formulas.
  • Use DAX to solve real-world problems.

📖 Warm-up Story: The Magic Calculator

Chidi has a magic calculator. He can ask it questions like: "What is the total sales for this year?" or "What is the average score of students?" and it answers instantly. The magic calculator is like DAX – it can answer any question about your data. You just need to write the right formula, and the answer appears!

📚 Main Lessons (15 Lessons)

Lesson 1: What is DAX?

Definition: DAX stands for Data Analysis Expressions. It's a language used to create calculations in Power BI.

Why important: DAX allows you to ask questions and get answers from your data.

Simple explanation: It's like a magic language that turns data into answers.

Real-life example: A store uses DAX to calculate total sales.

School example: A teacher uses DAX to calculate average scores.

Home example: You use DAX to calculate total expenses.

Nigerian example: A bank uses DAX to calculate total deposits.

Illustration:

Data + DAX = Answers
Sales Table + DAX = Total Sales

Mini summary: DAX is the language for creating calculations in Power BI.

Lesson 2: Calculated Columns vs Measures

Definition: Calculated columns are added to a table and evaluated row by row. Measures are calculated on the fly based on the context.

Why important: Knowing the difference helps you use DAX correctly.

Simple explanation: Calculated columns are like permanent additions. Measures are like temporary answers that change.

Real-life example: Calculated column: "Profit" = [Sales] - [Cost]. Measure: Total Sales = SUM([Sales]).

School example: Calculated column: "Total Score" = [Exam] + [Assignment]. Measure: Average Score = AVERAGE([Total Score]).

Home example: Calculated column: "Adjusted Price" = [Price] + [Tax]. Measure: Total Budget = SUM([Adjusted Price]).

Nigerian example: Calculated column: "Net Salary" = [Gross] - [Tax]. Measure: Total Payroll = SUM([Net Salary]).

Illustration:

Calculated Column: Adds data to a table (row by row).
Measure: Calculates data on the fly (dynamic).

Mini summary: Calculated columns are row-level; measures are dynamic.

Lesson 3: Basic DAX Functions – SUM

Definition: SUM adds all the numbers in a column.

Why important: It's the most used function for totals.

Simple explanation: It adds up numbers, just like a calculator.

Real-life example: Total Sales = SUM(Sales[Amount]).

School example: Total Marks = SUM(Grades[Score]).

Home example: Total Expenses = SUM(Budget[Amount]).

Nigerian example: Total Votes = SUM(Votes[Count]).

How to write: Measure = SUM(Table[Column]).

Illustration:

Sales[Amount] = [100, 150, 200]
SUM(Sales[Amount]) = 450

Mini summary: SUM adds numbers.

Lesson 4: Basic DAX Functions – AVERAGE

Definition: AVERAGE calculates the average of a column.

Why important: To find the typical value.

Simple explanation: It adds all numbers and divides by the count.

Real-life example: Average Sales = AVERAGE(Sales[Amount]).

School example: Average Score = AVERAGE(Grades[Score]).

Home example: Average Expense = AVERAGE(Budget[Amount]).

Nigerian example: Average Rainfall = AVERAGE(Weather[Rainfall]).

How to write: Measure = AVERAGE(Table[Column]).

Illustration:

Sales[Amount] = [100, 150, 200]
AVERAGE(Sales[Amount]) = 150

Mini summary: AVERAGE finds the mean.

Lesson 5: Basic DAX Functions – COUNT

Definition: COUNT counts the number of rows in a column.

Why important: To know how many items.

Simple explanation: It counts rows.

Real-life example: Number of Orders = COUNT(Orders[OrderID]).

School example: Number of Students = COUNT(Students[StudentID]).

Home example: Number of Expenses = COUNT(Budget[Amount]).

Nigerian example: Number of Voters = COUNT(Voters[VoterID]).

How to write: Measure = COUNT(Table[Column]).

Illustration:

Sales[Amount] = [100, 150, 200]
COUNT(Sales[Amount]) = 3

Mini summary: COUNT counts rows.

Lesson 6: Basic DAX Functions – MAX and MIN

Definition: MAX finds the highest value, MIN finds the lowest value.

Why important: To know the extremes.

Simple explanation: MAX gives the biggest, MIN gives the smallest.

Real-life example: Highest Sales = MAX(Sales[Amount]).

School example: Highest Score = MAX(Grades[Score]).

Home example: Highest Expense = MAX(Budget[Amount]).

Nigerian example: Maximum Rainfall = MAX(Weather[Rainfall]).

How to write: Measure = MAX(Table[Column]).

Illustration:

Sales[Amount] = [100, 150, 200]
MAX = 200, MIN = 100

Mini summary: MAX finds the largest, MIN finds the smallest.

Lesson 7: The CALCULATE Function

Definition: CALCULATE changes the context in which a calculation is performed.

Why important: It's the most powerful function in DAX.

Simple explanation: It's like a magnifying glass that focuses on specific data.

Real-life example: Total Sales for Year 2025 = CALCULATE(SUM(Sales[Amount]), Sales[Year] = 2025).

School example: Average Score for Math = CALCULATE(AVERAGE(Grades[Score]), Grades[Subject] = "Math").

Home example: Total Expenses for Food = CALCULATE(SUM(Budget[Amount]), Budget[Category] = "Food").

Nigerian example: Total Votes in Lagos = CALCULATE(SUM(Votes[Count]), Votes[State] = "Lagos").

How to write: Measure = CALCULATE(expression, filter).

Illustration:

CALCULATE(SUM(Sales[Amount]), Sales[Year] = 2025)
→ Sum of sales only for 2025.

Mini summary: CALCULATE changes the calculation context.

Lesson 8: The FILTER Function

Definition: FILTER returns a table that is filtered based on a condition.

Why important: It's used inside CALCULATE to apply complex filters.

Simple explanation: It's like a sieve that only keeps specific rows.

Real-life example: Total Sales for Products with Price > 100 = CALCULATE(SUM(Sales[Amount]), FILTER(Products, Products[Price] > 100)).

School example: Average Score for Students with Attendance > 90% = CALCULATE(AVERAGE(Grades[Score]), FILTER(Students, Students[Attendance] > 0.9)).

Home example: Total Expenses for Categories with Amount > 1000 = CALCULATE(SUM(Budget[Amount]), FILTER(Budget, Budget[Amount] > 1000)).

Nigerian example: Total Votes for States with Population > 1M = CALCULATE(SUM(Votes[Count]), FILTER(States, States[Population] > 1000000)).

Illustration:

FILTER(Products, Products[Price] > 100)
→ Only keeps products with price > 100.

Mini summary: FILTER creates a filtered table.

Lesson 9: Time Intelligence – TOTALYTD

Definition: TOTALYTD calculates the year-to-date total.

Why important: To track cumulative totals over time.

Simple explanation: It adds up values from the start of the year to the current date.

Real-life example: Sales YTD = TOTALYTD(SUM(Sales[Amount]), Dates[Date]).

School example: Marks YTD = TOTALYTD(SUM(Grades[Score]), Dates[Date]).

Home example: Expenses YTD = TOTALYTD(SUM(Budget[Amount]), Dates[Date]).

Nigerian example: Revenue YTD = TOTALYTD(SUM(Revenue[Amount]), Dates[Date]).

How to write: Measure = TOTALYTD(expression, dates column).

Illustration:

TOTALYTD(SUM(Sales[Amount]), Calendar[Date])
→ Total sales from Jan 1 to today.

Mini summary: TOTALYTD gives year-to-date totals.

Lesson 10: Time Intelligence – SAMEPERIODLASTYEAR

Definition: SAMEPERIODLASTYEAR returns the same period in the previous year.

Why important: To compare performance year-over-year.

Simple explanation: It gives you the same dates but one year ago.

Real-life example: Sales Last Year = CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Dates[Date])).

School example: Scores Last Year = CALCULATE(AVERAGE(Grades[Score]), SAMEPERIODLASTYEAR(Dates[Date])).

Home example: Expenses Last Year = CALCULATE(SUM(Budget[Amount]), SAMEPERIODLASTYEAR(Dates[Date])).

Nigerian example: Revenue Last Year = CALCULATE(SUM(Revenue[Amount]), SAMEPERIODLASTYEAR(Dates[Date])).

Illustration:

CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date]))
→ Sales for the same period last year.

Mini summary: SAMEPERIODLASTYEAR compares with the previous year.

Lesson 11: The ALL Function

Definition: ALL removes all filters from a table or column.

Why important: Useful for calculating percentages of totals.

Simple explanation: It ignores any filters and looks at everything.

Real-life example: % of Total Sales = DIVIDE(SUM(Sales[Amount]), CALCULATE(SUM(Sales[Amount]), ALL(Sales))).

School example: % of Total Marks = DIVIDE(SUM(Grades[Score]), CALCULATE(SUM(Grades[Score]), ALL(Grades))).

Home example: % of Total Expenses = DIVIDE(SUM(Budget[Amount]), CALCULATE(SUM(Budget[Amount]), ALL(Budget))).

Nigerian example: % of Total Votes = DIVIDE(SUM(Votes[Count]), CALCULATE(SUM(Votes[Count]), ALL(Votes))).

Illustration:

DIVIDE(SUM(Sales[Amount]), CALCULATE(SUM(Sales[Amount]), ALL(Sales)))
→ Percentage of each product's sales out of total.

Mini summary: ALL removes filters.

Lesson 12: Row Context and Filter Context

Definition: Row context refers to a single row being evaluated. Filter context refers to the filters applied to the data.

Why important: Understanding context is key to writing correct DAX.

Simple explanation: Row context is like looking at one student's score. Filter context is like looking at all students from a particular class.

Real-life example: Row context: calculating profit for each product. Filter context: calculating total sales for a region.

School example: Row context: calculating total marks for a student. Filter context: calculating average marks for a subject.

Home example: Row context: calculating cost per item. Filter context: calculating total cost for a category.

Nigerian example: Row context: calculating tax per citizen. Filter context: calculating total tax for a state.

Illustration:

Row Context: Each row is evaluated individually.
Filter Context: All rows that meet certain criteria.

Mini summary: Row context = one row; Filter context = filtered rows.

Lesson 13: The DIVIDE Function

Definition: DIVIDE handles division safely, returning an alternate value if the denominator is zero.

Why important: Prevents errors in calculations.

Simple explanation: It's like a safety net for division.

Real-life example: Sales per Product = DIVIDE(SUM(Sales[Amount]), COUNT(Products[ProductID]), 0).

School example: Average per Student = DIVIDE(SUM(Grades[Score]), COUNT(Students[StudentID]), 0).

Home example: Average per Category = DIVIDE(SUM(Budget[Amount]), COUNT(Categories[CategoryID]), 0).

Nigerian example: Average per State = DIVIDE(SUM(Population[Total]), COUNT(States[StateID]), 0).

How to write: DIVIDE(numerator, denominator, alternate result).

Illustration:

DIVIDE(10, 0, 0) → 0
DIVIDE(10, 2, 0) → 5

Mini summary: DIVIDE safely handles division by zero.

Lesson 14: Common DAX Patterns

Definition: Common patterns are frequently used DAX formulas.

Why important: They save time and are proven to work.

Simple explanation: It's like using a recipe instead of inventing a new dish.

  • Total Sales = SUM(Sales[Amount])
  • Sales YTD = TOTALYTD(SUM(Sales[Amount]), Calendar[Date])
  • Sales LY = CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date]))
  • % of Total = DIVIDE(SUM(Sales[Amount]), CALCULATE(SUM(Sales[Amount]), ALL(Sales)))

Illustration:

Measure: Total Sales = SUM(Sales[Amount])
Measure: Sales YTD = TOTALYTD([Total Sales], Calendar[Date])
Measure: % of Total = DIVIDE([Total Sales], CALCULATE([Total Sales], ALL(Sales)))

Mini summary: Use common patterns for efficient DAX.

Lesson 15: Best Practices for DAX

Definition: Tips for writing efficient and accurate DAX formulas.

Why important: Good DAX is fast, accurate, and easy to understand.

Simple explanation: It's like following rules to build a strong house.

  • Use measures instead of calculated columns when possible.
  • Use CALCULATE with FILTER for complex conditions.
  • Use DIVIDE instead of / for safe division.
  • Keep formulas simple and readable.
  • Test your measures with sample data.

Illustration:

1. Use measures for dynamic calculations.
2. Use CALCULATE for context changes.
3. Use DIVIDE for safe division.
4. Document your measures.

Mini summary: Follow best practices for quality DAX.

📖 Key Vocabulary (with simple definitions)

  • DAX: Data Analysis Expressions – a language for calculations.
  • Calculated Column: A column added to a table, evaluated row by row.
  • Measure: A calculation evaluated on the fly.
  • SUM: Adds numbers.
  • AVERAGE: Calculates the mean.
  • COUNT: Counts rows.
  • MAX: Finds the highest value.
  • MIN: Finds the lowest value.
  • CALCULATE: Changes the calculation context.
  • FILTER: Creates a filtered table.
  • ALL: Removes filters.
  • DIVIDE: Safely divides numbers.
  • Time Intelligence: Functions for date calculations.

🧠 Important Concepts

  • DAX is the language of Power BI calculations.
  • Calculated columns are row-level, measures are dynamic.
  • CALCULATE is the most powerful DAX function.
  • Time intelligence functions help with date analysis.
  • Context (row context and filter context) is key to DAX.

🔢 Step-by-Step Explanations

How to Create a Measure in Power BI:

  1. Open Power BI Desktop.
  2. In the Fields pane, right-click on a table.
  3. Select "New Measure".
  4. Write your DAX formula in the formula bar.
  5. Press Enter.

How to Create a Calculated Column:

  1. Open Power BI Desktop.
  2. In the Fields pane, right-click on a table.
  3. Select "New Column".
  4. Write your DAX formula.
  5. Press Enter.

🌍 Real-life Examples

  • Retail: Use DAX to calculate total sales, profit margins, and year-over-year growth.
  • Healthcare: Use DAX to calculate patient visits, average length of stay, and readmission rates.
  • Finance: Use DAX to calculate revenue, expenses, and net income.

🇳🇬 Nigerian Examples

  • Election: Use DAX to calculate total votes per party, voter turnout, and percentage of votes.
  • Agriculture: Use DAX to calculate total crop yield, average yield per state, and year-over-year comparison.
  • Telecom: Use DAX to calculate total call minutes, average call duration, and revenue per customer.

🎈 Fun Examples Children Can Relate To

  • Toys: Use DAX to calculate total toys sold, average price per toy, and highest selling toy.
  • Candy: Use DAX to calculate total candy sales, average sales per day, and month-to-date sales.
  • Games: Use DAX to calculate total game scores, average score per player, and high score.

🏠 Everyday Examples

  • Budget: Use DAX to calculate total expenses, average expense per category, and year-to-date spending.
  • Chores: Use DAX to calculate total chores completed, average chores per day, and most common chore.
  • School: Use DAX to calculate total marks, average marks, and highest marks per subject.

👩‍🏫 Teacher Notes

  • Start with simple functions and gradually introduce CALCULATE.
  • Emphasize the importance of context.
  • Use real-world datasets for practice.

👨‍👩‍👦 Parent Tips

  • Help your child create simple measures with real data (e.g., total allowance).
  • Discuss how DAX answers questions like "How much did I spend this month?"

💡 Interesting Facts

  • DAX is similar to Excel formulas but more powerful.
  • DAX has over 200 functions.
  • CALCULATE is considered the most important DAX function.

❓ Did You Know?

Did you know that DAX was originally developed for Power Pivot in Excel? Now it's used in Power BI, Analysis Services, and even in Excel!

🔔 Remember This

  • DAX is the language of Power BI calculations.
  • Measures are dynamic, calculated columns are static.
  • CALCULATE is the most powerful function.
  • Context is crucial in DAX.

⚠️ Common Mistakes

  • Using a calculated column when a measure is needed – causes performance issues.
  • Forgetting to use CALCULATE for context changes.
  • Dividing by zero without DIVIDE – causes errors.
  • Ignoring filter context – leads to wrong results.

✅ Best Practices

  • Use measures for aggregations.
  • Use CALCULATE to change context.
  • Use DIVIDE for safe division.
  • Test your measures thoroughly.
  • Document your DAX formulas.

📊 ASCII Illustrations

Calculated Column vs Measure

Calculated Column:
+----------+----------+----------+
| Product  | Price    | Tax      |
+----------+----------+----------+
| Toy      | 100      | = Price*0.1 (calculated row by row) |
+----------+----------+----------+

Measure:
Total Sales = SUM(Sales[Amount])  (dynamic calculation)

CALCULATE Flow

Expression  →  CALCULATE  →  Result
   ↓              ↓
 SUM(Sales)   Filter: Year = 2025
   ↓              ↓
   →  CALCULATE(SUM(Sales), Sales[Year]=2025)  →  Total Sales for 2025

📋 Comparison Tables

Calculated Column vs Measure

FeatureCalculated ColumnMeasure
EvaluationRow by rowOn the fly
StorageStored in tableNot stored
PerformanceSlowerFaster
Use caseRow-level calculationsAggregations

Basic DAX Functions

FunctionWhat it doesExample
SUMAdds numbersSUM(Sales[Amount])
AVERAGECalculates meanAVERAGE(Sales[Amount])
COUNTCounts rowsCOUNT(Sales[OrderID])
MAXFinds highestMAX(Sales[Amount])
MINFinds lowestMIN(Sales[Amount])

📝 End-of-Module Summary

Congratulations! You have completed Module Fourteen on Introduction to DAX. You learned:

  • What DAX is and how it's used.
  • The difference between calculated columns and measures.
  • Basic DAX functions: SUM, AVERAGE, COUNT, MAX, MIN.
  • How to use CALCULATE to change context.
  • Time intelligence functions like TOTALYTD and SAMEPERIODLASTYEAR.
  • How to use FILTER and ALL.
  • About row context and filter context.
  • Best practices for writing DAX.

You now have the skills to create powerful calculations and make your reports truly intelligent!

❓ Frequently Asked Questions (10)

  1. What is DAX? – Data Analysis Expressions, a language for calculations in Power BI.
  2. What is a measure? – A dynamic calculation.
  3. What is a calculated column? – A column added to a table.
  4. What does SUM do? – Adds numbers.
  5. What does AVERAGE do? – Calculates the mean.
  6. What does COUNT do? – Counts rows.
  7. What is CALCULATE? – A function that changes context.
  8. What is TOTALYTD? – Calculates year-to-date totals.
  9. What is the difference between row context and filter context? – Row context is one row; filter context is filtered rows.
  10. What is DIVIDE used for? – Safe division.

📝 Review Questions (15)

  1. What is DAX?
  2. What is a measure?
  3. What is a calculated column?
  4. What does SUM do?
  5. What does AVERAGE do?
  6. What does COUNT do?
  7. What does MAX do?
  8. What does MIN do?
  9. What is CALCULATE?
  10. What is TOTALYTD?
  11. What is SAMEPERIODLASTYEAR?
  12. What is FILTER?
  13. What is ALL?
  14. What is the difference between row context and filter context?
  15. What is DIVIDE used for?

✍️ Fill-in-the-Blank Exercises

  1. ______ is a language for calculations in Power BI.
  2. A ______ is a dynamic calculation.
  3. ______ adds numbers.
  4. ______ changes the calculation context.
  5. ______ calculates year-to-date totals.

✅ True or False Exercises

  1. DAX stands for Data Analysis Expressions. (True)
  2. A calculated column is dynamic. (False)
  3. A measure is evaluated row by row. (False)
  4. CALCULATE changes context. (True)
  5. TOTALYTD calculates month-to-date totals. (False)

🔘 Multiple Choice Questions (15 with answers)

  1. What is DAX?
    a) Data Analysis Expressions b) Data Aggregation X c) Direct Access X d) Digital Analysis X
    Answer: a
  2. What is a measure?
    a) A dynamic calculation b) A static column c) A table d) A chart
    Answer: a
  3. What does SUM do?
    a) Counts rows b) Adds numbers c) Averages numbers d) Finds the maximum
    Answer: b
  4. What does AVERAGE do?
    a) Adds numbers b) Counts rows c) Calculates the mean d) Finds the minimum
    Answer: c
  5. What does COUNT do?
    a) Adds numbers b) Counts rows c) Averages numbers d) Finds the maximum
    Answer: b
  6. What is CALCULATE?
    a) A function that changes context b) A function that adds numbers c) A function that counts rows d) A function that finds the maximum
    Answer: a
  7. What is TOTALYTD?
    a) Year-to-date total b) Month-to-date total c) Day-to-date total d) Quarter-to-date total
    Answer: a
  8. What is SAMEPERIODLASTYEAR used for?
    a) Comparing with previous year b) Comparing with next year c) Comparing with current year d) Comparing with previous month
    Answer: a
  9. What is FILTER used for?
    a) Creating a filtered table b) Removing filters c) Adding columns d) Deleting rows
    Answer: a
  10. What is ALL used for?
    a) Removing filters b) Adding filters c) Creating tables d) Counting rows
    Answer: a
  11. What is DIVIDE used for?
    a) Safe division b) Adding numbers c) Counting rows d) Finding maximum
    Answer: a
  12. What is row context?
    a) Evaluating one row at a time b) Evaluating all rows c) Removing filters d) Adding filters
    Answer: a
  13. What is filter context?
    a) Filters applied to data b) One row c) A new column d) A measure
    Answer: a
  14. Which is a measure?
    a) SUM(Sales[Amount]) b) Sales[Amount] c) Sales d) Amount
    Answer: a
  15. Which is a calculated column?
    a) [Profit] = [Sales] - [Cost] b) SUM(Sales[Amount]) c) AVERAGE(Sales[Amount]) d) COUNT(Sales[OrderID])
    Answer: a

🔗 Matching Exercises

Match the function to its description:

FunctionDescription
1. SUMA. Calculates the mean
2. AVERAGEB. Adds numbers
3. COUNTC. Finds the highest value
4. MAXD. Counts rows
5. CALCULATEE. Changes context

Answers: 1-B, 2-A, 3-D, 4-C, 5-E

✍️ Short Answer Questions

  1. What is DAX and why is it important?
  2. Explain the difference between a calculated column and a measure.
  3. What is CALCULATE and when would you use it?
  4. What is time intelligence? Give an example.
  5. Why is DIVIDE better than the / operator?

📖 Scenario-based Exercises

Scenario 1: You have a sales table with columns: Product, Amount, Date. Write a DAX measure to calculate total sales for the year 2025.

Scenario 2: You have a student grades table with columns: Student, Subject, Score. Write a DAX measure to calculate the average score for Math.

👥 Group Activity

In groups, choose a dataset (e.g., sales data). Create at least five DAX measures: Total Sales, Average Sales, Max Sales, Min Sales, and Sales YTD. Present your measures and explain how they work.

🧑‍🎓 Individual Activity

Load a sample dataset into Power BI. Create a calculated column (e.g., Profit = Sales - Cost) and a measure (e.g., Total Sales = SUM(Sales)). Write at least three more measures of your choice.

💬 Classroom Discussion Questions

  • Why is DAX important for data analysis?
  • What are some challenges you faced when writing DAX?
  • How does context affect DAX calculations?

🛠️ Mini Project

Project: DAX Sales Dashboard

Build a sales dashboard using DAX. Include measures for: Total Sales, Total Sales YTD, Sales Last Year, Average Sales per Product, and % of Total Sales. Add a chart that shows sales by month. Use time intelligence functions.

📋 Practical Assignment

Download a dataset with at least 1,000 rows. Create a data model and write at least 10 DAX measures. Include measures that use CALCULATE, FILTER, and time intelligence. Document your measures.

🏆 Challenge Exercise

Write a DAX measure that calculates the moving average of sales over the last 3 months. Use CALCULATE and FILTER. Test it with sample data.

📝 Quiz Answers

Fill-in-the-Blank: 1. DAX, 2. measure, 3. SUM, 4. CALCULATE, 5. TOTALYTD

True/False: 1-T, 2-F, 3-F, 4-T, 5-F

Matching: 1-B, 2-A, 3-D, 4-C, 5-E

🔑 Key Takeaways

  • DAX is the language for calculations in Power BI.
  • Measures are dynamic and powerful.
  • CALCULATE is the most important DAX function.
  • Time intelligence helps with date-based analysis.
  • Always test your DAX measures.

📖 Preparation for the Next Module

In Module Fifteen, we will learn about Advanced DAX Patterns – we will explore more complex calculations like ranking, running totals, and dynamic segmentation. You will become a true DAX master!

Before the next class, practice writing DAX measures with CALCULATE and time intelligence. Try to create at least five different measures.


© 2025 Certified Power Query for Data Analysis Expert – Module Fourteen

16

Module Fifteen

Module 15 · Power Query for Data Analysis Expert

⭐ Module Fifteen: Advanced DAX Patterns

Hello, young data explorer! Welcome to Module Fifteen. In this module, we will learn advanced DAX patterns. These are powerful formulas that solve complex problems. Think of them as special tricks that make your reports even smarter. You will learn how to rank products, calculate running totals, and compare different time periods. By the end of this module, you will be a DAX master!

🎯 Learning Objectives

  • Learn how to create rankings with RANKX.
  • Learn how to calculate running totals.
  • Learn how to use EARLIER for row-based calculations.
  • Learn about dynamic segmentation.
  • Learn how to compare with previous periods.
  • Learn about grouping and summarizing with DAX.
  • Learn how to use variables (VAR) for cleaner code.
  • Understand the importance of evaluation context.
  • Learn how to debug DAX formulas.
  • Apply advanced DAX patterns to real-world problems.

📖 Warm-up Story: The Smart Scoreboard

Chidi loves sports. He has a scoreboard that shows players' scores. But he wants more: he wants to rank players, show cumulative scores, and compare this season with last season. He uses DAX to add these features. Now his scoreboard is the smartest one in the whole school! That's what advanced DAX patterns do – they make your reports smarter and more insightful.

📚 Main Lessons (15 Lessons)

Lesson 1: What are Advanced DAX Patterns?

Definition: Advanced DAX patterns are complex formulas that solve specific analytical problems.

Why important: They help you get deeper insights from your data.

Simple explanation: It's like learning advanced magic spells after you've mastered the basics.

Real-life example: Ranking top-selling products.

School example: Ranking students by grades.

Home example: Ranking expenses by category.

Nigerian example: Ranking states by population.

Illustration:

Basic DAX: SUM, AVERAGE
Advanced DAX: RANKX, RUNNING TOTAL, COMPARE PERIODS

Mini summary: Advanced patterns solve complex problems.

Lesson 2: RANKX – Ranking Items

Definition: RANKX returns the rank of a value in a list.

Why important: To see who is first, second, etc.

Simple explanation: It tells you the position of an item (1st, 2nd, 3rd).

Real-life example: Rank products by sales.

School example: Rank students by score.

Home example: Rank expenses by amount.

Nigerian example: Rank states by population.

How to write: Rank = RANKX(ALL(Table[Column]), SUM(Table[Value]), , DESC).

Illustration:

Products: A(100), B(200), C(150)
RANKX → A=3, B=1, C=2

Mini summary: RANKX gives ranks to items.

Lesson 3: RANKX with Ties

Definition: When two items have the same value, they get the same rank.

Why important: To handle ties fairly.

Simple explanation: If two students have the same score, they both get the same rank.

Real-life example: Two products with same sales both get rank 1.

School example: Two students with same score both get rank 1.

Home example: Two expenses with same amount both get rank 1.

Nigerian example: Two states with same population both get rank 1.

How to handle: Use RANKX with ties parameter or calculate dense rank.

Illustration:

Scores: 100, 100, 90
RANKX → 1, 1, 3 (skip 2)
Dense Rank → 1, 1, 2 (no skip)

Mini summary: Ties can be handled with rank options.

Lesson 4: Running Totals

Definition: A running total adds up values cumulatively over time.

Why important: To track cumulative performance.

Simple explanation: It's like a countdown that keeps adding.

Real-life example: Cumulative sales over months.

School example: Cumulative marks over tests.

Home example: Cumulative expenses over weeks.

Nigerian example: Cumulative revenue over years.

How to write: Running Total = CALCULATE(SUM(Table[Value]), FILTER(ALL(Table[Date]), Table[Date] <= MAX(Table[Date]))).

Illustration:

Month Sales: Jan=100, Feb=150, Mar=200
Running Total: Jan=100, Feb=250, Mar=450

Mini summary: Running totals add cumulatively.

Lesson 5: Moving Averages

Definition: A moving average calculates the average over a moving window of time.

Why important: Smooths out fluctuations to see trends.

Simple explanation: It's like a smooth line through your data.

Real-life example: 3-month moving average of sales.

School example: Moving average of test scores.

Home example: Moving average of daily expenses.

Nigerian example: Moving average of monthly rainfall.

How to write: Moving Avg = AVERAGEX(DATESINPERIOD(Calendar[Date], LASTDATE(Calendar[Date]), -3, MONTH), [Total Sales]).

Illustration:

Sales: Jan=100, Feb=150, Mar=200, Apr=180
3-Month Moving Avg (Apr): (150+200+180)/3 = 176.7

Mini summary: Moving averages smooth data.

Lesson 6: EARLIER – Row-based Calculations

Definition: EARLIER returns the value of a column from the outer row context.

Why important: Useful when you need to compare a row to other rows.

Simple explanation: It looks at the current row from an earlier context.

Real-life example: Calculate how much each product contributes to total sales.

School example: Calculate how much each student contributes to total marks.

Home example: Calculate how much each category contributes to total expenses.

Nigerian example: Calculate how much each state contributes to total population.

How to write: Contribution = [Value] / CALCULATE(SUM(Table[Value]), ALL(Table)).

Illustration:

Product Sales: A=100, B=200, C=300
Contribution: A=100/600=16.7%, B=33.3%, C=50%

Mini summary: EARLIER accesses outer context.

Lesson 7: Dynamic Segmentation

Definition: Dynamic segmentation groups data into categories based on values (e.g., High, Medium, Low).

Why important: To classify data for better understanding.

Simple explanation: It's like sorting items into boxes based on size.

Real-life example: Segment customers by spending amount.

School example: Segment students by score (A, B, C).

Home example: Segment expenses by amount (High, Medium, Low).

Nigerian example: Segment states by population (Large, Medium, Small).

How to write: Segment = SWITCH(TRUE(), [Value] > 100, "High", [Value] > 50, "Medium", "Low").

Illustration:

Sales: 150 → High, 75 → Medium, 30 → Low

Mini summary: Dynamic segmentation categorizes data.

Lesson 8: Comparing with Previous Periods

Definition: Compare current period with previous period (e.g., this month vs last month).

Why important: To measure growth or decline.

Simple explanation: It's like comparing your scores from today and yesterday.

Real-life example: Sales this month vs last month.

School example: Scores this test vs previous test.

Home example: Expenses this week vs last week.

Nigerian example: Revenue this quarter vs previous quarter.

How to write: Previous Period = CALCULATE(SUM(Table[Value]), PREVIOUSMONTH(Calendar[Date])).

Illustration:

Current Month Sales: 200
Previous Month Sales: 150
Difference = 50

Mini summary: Compare current and previous periods.

Lesson 9: Using Variables (VAR) in DAX

Definition: VAR allows you to store a value in a variable for reuse.

Why important: Makes formulas cleaner and faster.

Simple explanation: It's like storing a number in your memory to use later.

Real-life example: VAR TotalSales = SUM(Sales[Amount]); RETURN TotalSales * 0.1.

School example: VAR TotalMarks = SUM(Grades[Score]); RETURN TotalMarks / 100.

Home example: VAR TotalExpenses = SUM(Budget[Amount]); RETURN TotalExpenses * 0.2.

Nigerian example: VAR TotalVotes = SUM(Votes[Count]); RETURN TotalVotes / 10000.

How to write: VAR name = expression RETURN expression.

Illustration:

VAR TotalSales = SUM(Sales[Amount])
VAR TotalCost = SUM(Sales[Cost])
RETURN TotalSales - TotalCost

Mini summary: VAR makes DAX cleaner and reusable.

Lesson 10: GROUPBY – Grouping in DAX

Definition: GROUPBY creates a summary table based on grouping columns.

Why important: To create custom aggregations.

Simple explanation: It's like Group By in Power Query but in DAX.

Real-life example: Group sales by product and sum.

School example: Group grades by subject and average.

Home example: Group expenses by category and sum.

Nigerian example: Group votes by state and count.

How to write: GROUPBY(Table, Column, "NewColumn", SUMX(CURRENTGROUP(), [Value])).

Illustration:

GROUPBY(Sales, Product, "TotalSales", SUMX(CURRENTGROUP(), Sales[Amount]))

Mini summary: GROUPBY creates custom summaries.

Lesson 11: SUMMARIZE – Advanced Grouping

Definition: SUMMARIZE creates a summary table with grouping and aggregations.

Why important: More powerful than GROUPBY.

Simple explanation: It's like GROUPBY but with more options.

Real-life example: SUMMARIZE(Sales, Product, Category, "TotalSales", SUM(Sales[Amount])).

School example: SUMMARIZE(Grades, Subject, Teacher, "AvgScore", AVERAGE(Grades[Score])).

Home example: SUMMARIZE(Budget, Category, Month, "Total", SUM(Budget[Amount])).

Nigerian example: SUMMARIZE(Votes, State, Party, "TotalVotes", SUM(Votes[Count])).

Illustration:

SUMMARIZE(Sales, Product, "TotalSales", SUM(Sales[Amount]))

Mini summary: SUMMARIZE is a powerful grouping function.

Lesson 12: Using CALCULATE with Time Intelligence

Definition: Combine CALCULATE with time functions for powerful time-based analysis.

Why important: To answer questions like "Sales for the same period last year".

Simple explanation: It's like asking "What happened this time last year?"

Real-life example: Sales LY = CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date])).

School example: Scores LY = CALCULATE(AVERAGE(Grades[Score]), SAMEPERIODLASTYEAR(Calendar[Date])).

Home example: Expenses LY = CALCULATE(SUM(Budget[Amount]), SAMEPERIODLASTYEAR(Calendar[Date])).

Nigerian example: Votes LY = CALCULATE(SUM(Votes[Count]), SAMEPERIODLASTYEAR(Calendar[Date])).

Illustration:

CALCULATE([Total Sales], SAMEPERIODLASTYEAR(Calendar[Date]))

Mini summary: CALCULATE with time intelligence is powerful.

Lesson 13: Debugging DAX Formulas

Definition: Debugging means finding and fixing errors in your DAX formulas.

Why important: Everyone makes mistakes. You need to fix them.

Simple explanation: It's like finding a needle in a haystack.

Real-life example: A measure returns wrong results. You check the formula.

School example: A calculation is incorrect. You review the logic.

Home example: A total is wrong. You trace back.

Nigerian example: A report has errors. You debug.

Tips: Use variables to break down complex formulas. Test with sample data. Check context.

Illustration:

1. Check the formula.
2. Test with small data.
3. Use variables to simplify.
4. Check filter context.

Mini summary: Debugging fixes errors in DAX.

Lesson 14: Common Advanced DAX Patterns

Definition: Patterns that are frequently used in real-world scenarios.

Why important: They save time and are proven to work.

Simple explanation: It's like using a template for your formulas.

  • Ranking: RANKX(ALL(Table[Column]), [Measure])
  • Running Total: CALCULATE([Measure], FILTER(ALL(Calendar), Calendar[Date] <= MAX(Calendar[Date])))
  • Compare with Previous Year: CALCULATE([Measure], SAMEPERIODLASTYEAR(Calendar[Date]))
  • % of Total: DIVIDE([Measure], CALCULATE([Measure], ALL(Table)))

Illustration:

Pattern: Rank Products by Sales
Rank = RANKX(ALL(Products[ProductID]), [Total Sales], , DESC)

Mini summary: Common patterns make DAX easier.

Lesson 15: Best Practices for Advanced DAX

Definition: Tips for writing efficient and accurate advanced DAX.

Why important: Good DAX is fast, reliable, and easy to maintain.

Simple explanation: It's like following rules to build a strong building.

  • Use variables to simplify complex formulas.
  • Use CALCULATE and FILTER carefully.
  • Test measures with sample data.
  • Optimize performance by reducing calculations.
  • Document your DAX formulas.

Illustration:

1. Use VAR to break down.
2. Test with sample.
3. Use CALCULATE wisely.
4. Document your code.

Mini summary: Best practices lead to quality DAX.

📖 Key Vocabulary (with simple definitions)

  • RANKX: Gives rank to items.
  • Running Total: Cumulative sum.
  • Moving Average: Average over a moving window.
  • EARLIER: Accesses outer row context.
  • Dynamic Segmentation: Categorizes data.
  • VAR: Variable to store values.
  • GROUPBY: Groups and aggregates.
  • SUMMARIZE: Advanced grouping.
  • Debugging: Finding and fixing errors.

🧠 Important Concepts

  • Advanced DAX solves complex problems.
  • RANKX gives ranks.
  • Running totals track cumulative performance.
  • Variables make DAX cleaner.
  • Always test and debug your formulas.

🔢 Step-by-Step Explanations

How to Create a Ranking Measure:

  1. Create a measure for the value you want to rank (e.g., Total Sales).
  2. Create a new measure: Rank = RANKX(ALL(Table[Column]), [Total Sales], , DESC).
  3. Use this measure in a table to see ranks.

How to Create a Running Total:

  1. Create a measure for the value (e.g., Total Sales).
  2. Create a new measure: Running Total = CALCULATE([Total Sales], FILTER(ALL(Calendar), Calendar[Date] <= MAX(Calendar[Date]))).
  3. Add this measure to a chart to see cumulative totals.

🌍 Real-life Examples

  • Retail: Rank products by sales, calculate running sales totals.
  • Healthcare: Rank hospitals by patient satisfaction, calculate cumulative cases.
  • Finance: Rank branches by revenue, calculate running profits.

🇳🇬 Nigerian Examples

  • Election: Rank parties by votes, calculate running total of votes.
  • Agriculture: Rank states by crop yield, calculate cumulative yield.
  • Telecom: Rank regions by call volume, calculate running call minutes.

🎈 Fun Examples Children Can Relate To

  • Toys: Rank toys by popularity, calculate running total of toys sold.
  • Candy: Rank candies by sales, calculate cumulative candy sales.
  • Games: Rank players by scores, calculate running total of game scores.

🏠 Everyday Examples

  • Budget: Rank categories by expense, calculate running total of expenses.
  • Chores: Rank chores by time, calculate cumulative time.
  • School: Rank subjects by scores, calculate running total of marks.

👩‍🏫 Teacher Notes

  • Start with RANKX and running totals as they are most commonly used.
  • Use real-world examples to make concepts relatable.
  • Encourage students to practice with sample data.

👨‍👩‍👦 Parent Tips

  • Help your child create a ranking for a list of items (e.g., favorite foods).
  • Discuss how running totals are used in everyday life (e.g., saving money).

💡 Interesting Facts

  • RANKX is one of the most used DAX functions.
  • Running totals are essential for financial analysis.
  • VAR was introduced to DAX to improve readability.

❓ Did You Know?

Did you know that you can use DAX to create a "ranking" that updates automatically as your data changes? That's the power of dynamic calculations!

🔔 Remember This

  • RANKX gives ranks to items.
  • Running totals show cumulative sums.
  • Moving averages smooth data.
  • VAR makes formulas cleaner.
  • Always test your DAX formulas.

⚠️ Common Mistakes

  • Using RANKX without ALL – rank is not calculated correctly.
  • Forgetting to use CALCULATE in running totals.
  • Not using VAR – formulas become complex and hard to read.
  • Ignoring context – leads to wrong results.

✅ Best Practices

  • Use ALL in RANKX to rank across all items.
  • Use CALCULATE with FILTER for running totals.
  • Use VAR to simplify complex formulas.
  • Test your measures with sample data.
  • Document your DAX formulas.

📊 ASCII Illustrations

RANKX Example

Products: A(100), B(200), C(150)
Rank: A=3, B=1, C=2

+----------+----------+--------+
| Product  | Sales    | Rank   |
+----------+----------+--------+
| A        | 100      | 3      |
| B        | 200      | 1      |
| C        | 150      | 2      |
+----------+----------+--------+

Running Total Example

Month Sales: Jan=100, Feb=150, Mar=200
Running Total: Jan=100, Feb=250, Mar=450

+----------+----------+-------------+
| Month    | Sales    | Running     |
|          |          | Total       |
+----------+----------+-------------+
| Jan      | 100      | 100         |
| Feb      | 150      | 250         |
| Mar      | 200      | 450         |
+----------+----------+-------------+

📋 Comparison Tables

RANKX vs DENSE RANK

ValueRANKXDENSE RANK
10011
10011
9032

Running Total vs Moving Average

FeatureRunning TotalMoving Average
PurposeCumulative sumSmooth trends
FormulaAdds all previousAverage of window
Use whenTracking progressIdentifying trends

📝 End-of-Module Summary

Congratulations! You have completed Module Fifteen on Advanced DAX Patterns. You learned:

  • How to use RANKX for rankings.
  • How to calculate running totals.
  • How to create moving averages.
  • How to use EARLIER and dynamic segmentation.
  • How to compare periods and use variables.
  • How to use GROUPBY and SUMMARIZE.
  • How to debug and follow best practices.

You are now a DAX master! You can solve any analytical problem with these advanced patterns.

❓ Frequently Asked Questions (10)

  1. What is RANKX? – A function that gives ranks to items.
  2. What is a running total? – A cumulative sum.
  3. What is a moving average? – Average over a moving window.
  4. What is EARLIER? – Accesses outer row context.
  5. What is dynamic segmentation? – Categorizing data on the fly.
  6. What is VAR? – A variable to store values.
  7. What is GROUPBY? – Groups and aggregates.
  8. What is SUMMARIZE? – Advanced grouping.
  9. How do you debug DAX? – Use variables, test with sample data.
  10. What is the difference between RANKX and DENSE RANK? – Dense rank doesn't skip numbers.

📝 Review Questions (15)

  1. What is RANKX used for?
  2. What is a running total?
  3. What is a moving average?
  4. What is EARLIER used for?
  5. What is dynamic segmentation?
  6. What is VAR used for?
  7. What is GROUPBY?
  8. What is SUMMARIZE?
  9. How do you debug a DAX formula?
  10. What is the difference between RANKX and DENSE RANK?
  11. How do you calculate a running total?
  12. How do you calculate a moving average?
  13. What is the purpose of dynamic segmentation?
  14. Why use variables in DAX?
  15. What is the most important advanced DAX pattern?

✍️ Fill-in-the-Blank Exercises

  1. ______ gives ranks to items.
  2. A ______ total adds up cumulatively.
  3. ______ stores a value for reuse.
  4. ______ is a function that groups and aggregates.
  5. ______ accesses outer row context.

✅ True or False Exercises

  1. RANKX gives ranks to items. (True)
  2. A running total is a moving average. (False)
  3. VAR stores values for reuse. (True)
  4. GROUPBY is used for filtering. (False)
  5. Debugging is fixing errors. (True)

🔘 Multiple Choice Questions (15 with answers)

  1. Which function gives ranks to items?
    a) SUM b) RANKX c) AVERAGE d) COUNT
    Answer: b
  2. What is a running total?
    a) A cumulative sum b) An average c) A maximum d) A minimum
    Answer: a
  3. What is VAR used for?
    a) Storing values b) Adding numbers c) Counting rows d) Ranking
    Answer: a
  4. What is GROUPBY used for?
    a) Grouping and aggregating b) Filtering c) Sorting d) Ranking
    Answer: a
  5. What is EARLIER used for?
    a) Accessing outer context b) Adding numbers c) Counting rows d) Ranking
    Answer: a
  6. What is a moving average?
    a) Average over a window b) Cumulative sum c) Maximum d) Minimum
    Answer: a
  7. What is dynamic segmentation?
    a) Categorizing data b) Adding numbers c) Counting rows d) Ranking
    Answer: a
  8. What is the purpose of debugging?
    a) Fixing errors b) Adding data c) Deleting data d) Sorting
    Answer: a
  9. Which is a best practice for DAX?
    a) Use VAR b) Ignore context c) Avoid testing d) Use complex formulas
    Answer: a
  10. What is SUMMARIZE used for?
    a) Advanced grouping b) Simple grouping c) Filtering d) Ranking
    Answer: a
  11. How do you calculate a running total?
    a) CALCULATE with FILTER b) SUM c) AVERAGE d) COUNT
    Answer: a
  12. How do you calculate a moving average?
    a) AVERAGEX with DATESINPERIOD b) SUM c) COUNT d) RANKX
    Answer: a
  13. What is the difference between RANKX and DENSE RANK?
    a) Dense rank doesn't skip numbers b) RANKX doesn't skip numbers c) Both are same d) Neither
    Answer: a
  14. What is the purpose of dynamic segmentation?
    a) To categorize data b) To add numbers c) To count rows d) To rank items
    Answer: a
  15. Why use variables in DAX?
    a) To simplify formulas b) To make them complex c) To slow down d) To hide data
    Answer: a

🔗 Matching Exercises

Match the function to its description:

FunctionDescription
1. RANKXA. Cumulative sum
2. Running TotalB. Gives ranks
3. VARC. Stores a value
4. GROUPBYD. Groups and aggregates

Answers: 1-B, 2-A, 3-C, 4-D

✍️ Short Answer Questions

  1. What is RANKX and how is it used?
  2. Explain the concept of a running total.
  3. What is the purpose of using VAR in DAX?
  4. How does dynamic segmentation work?
  5. What is the difference between GROUPBY and SUMMARIZE?

📖 Scenario-based Exercises

Scenario 1: You have a sales table. Write a DAX measure to rank products by total sales. Use RANKX.

Scenario 2: You have a student grades table. Write a DAX measure to calculate the running total of marks.

👥 Group Activity

In groups, choose a dataset and create at least five advanced DAX measures: ranking, running total, moving average, dynamic segmentation, and comparison with previous period. Present your findings.

🧑‍🎓 Individual Activity

Load a dataset into Power BI. Create a ranking measure, a running total, and a moving average. Use at least one VAR in your formulas. Document your work.

💬 Classroom Discussion Questions

  • Why is ranking important in data analysis?
  • How do running totals help in understanding trends?
  • What challenges did you face when creating advanced DAX measures?

🛠️ Mini Project

Project: Advanced Sales Dashboard

Build a sales dashboard that includes: ranking of products by sales, running total of sales, 3-month moving average of sales, dynamic segmentation of products (High, Medium, Low), and comparison of sales with previous year. Use at least 5 advanced DAX measures.

📋 Practical Assignment

Download a dataset with at least 5,000 rows. Create a data model and write at least 10 DAX measures, including ranking, running total, moving average, dynamic segmentation, and time intelligence. Document your measures.

🏆 Challenge Exercise

Write a DAX measure that calculates a 4-week moving average of sales. Use variables to make the formula clean and efficient. Test it with sample data.

📝 Quiz Answers

Fill-in-the-Blank: 1. RANKX, 2. running, 3. VAR, 4. GROUPBY, 5. EARLIER

True/False: 1-T, 2-F, 3-T, 4-F, 5-T

Matching: 1-B, 2-A, 3-C, 4-D

🔑 Key Takeaways

  • RANKX gives ranks to items.
  • Running totals show cumulative performance.
  • Moving averages smooth data.
  • VAR makes DAX cleaner.
  • Always test and debug your DAX formulas.
  • Advanced patterns solve complex problems.

📖 Preparation for the Next Module

In Module Sixteen, we will learn about Performance Optimization – how to make your Power Query and Power BI solutions run faster and more efficiently. You will learn tips and tricks to handle large datasets with ease. Get ready to become a performance expert!

Before the next class, practice writing advanced DAX measures with at least two different patterns.


© 2025 Certified Power Query for Data Analysis Expert – Module Fifteen

17

Module Sixteen

Module 16 · Power Query for Data Analysis Expert

⚡ Module Sixteen: Performance Optimization

Hello, young data explorer! Welcome to Module Sixteen. In this module, we will learn how to make our Power Query and Power BI solutions faster and more efficient. Imagine you have a car. You want it to go fast and use less fuel. Performance optimization is like tuning your car for speed and efficiency. By the end of this module, you will be able to handle large datasets with ease and make your reports load quickly.

🎯 Learning Objectives

  • Understand why performance matters.
  • Learn how to reduce data at the source.
  • Learn how to remove unnecessary columns and rows.
  • Learn how to use query folding.
  • Learn how to optimize data types.
  • Learn how to avoid expensive operations.
  • Learn about incremental refresh.
  • Learn how to optimize DAX.
  • Learn how to use performance analyzers.
  • Apply performance best practices.

📖 Warm-up Story: The Speedy Delivery Service

Chidi runs a delivery service. He wants to deliver packages as fast as possible. He learns to take shortcuts, reduce the weight of packages, and use faster vehicles. This is exactly what performance optimization does for data – it makes everything faster and more efficient!

📚 Main Lessons (15 Lessons)

Lesson 1: Why Performance Matters

Definition: Performance is how fast your data loads, refreshes, and responds.

Why important: Slow reports are frustrating and waste time.

Simple explanation: It's like waiting in a long queue – it's annoying and takes forever.

Real-life example: A company with a slow dashboard loses productivity.

School example: A slow grade calculator makes teachers wait.

Home example: A slow budget tracker is no fun.

Nigerian example: A slow election dashboard delays decisions.

Illustration:

Slow Report: 5 minutes to load
Fast Report: 5 seconds to load

Mini summary: Performance matters because time is valuable.

Lesson 2: Reduce Data at the Source

Definition: Only load the data you actually need.

Why important: Less data means faster processing.

Simple explanation: It's like only taking what you need from a buffet, not everything.

Real-life example: Instead of loading all columns, only load the ones you use.

School example: Instead of loading all student data, only load current students.

Home example: Instead of loading all transactions, only load this year's.

Nigerian example: Instead of loading all states, only load the ones you need.

How to do it: Use filters, select only necessary columns.

Illustration:

Before: Load 100 columns, 1M rows
After: Load 10 columns, 100K rows

Mini summary: Load only what you need.

Lesson 3: Remove Unnecessary Columns and Rows

Definition: Delete columns and rows that are not needed.

Why important: Reduces memory usage and speeds up processing.

Simple explanation: It's like throwing away things you don't use.

Real-life example: Remove columns like "CreatedBy" if you don't use them.

School example: Remove columns like "MiddleName" if not needed.

Home example: Remove columns like "StoreID" if not relevant.

Nigerian example: Remove columns like "BranchCode" if not needed.

How to do it: Use Remove Columns, Remove Rows.

Illustration:

Before: 50 columns
After: 10 columns (remove 40)

Mini summary: Remove unnecessary data.

Lesson 4: Query Folding

Definition: Query folding pushes transformations back to the source database, so they run faster.

Why important: Databases are optimized for data operations.

Simple explanation: It's like letting a chef cook in the kitchen instead of you trying to cook outside.

Real-life example: Filtering data in SQL before loading into Power Query.

School example: Filtering grades in the database before loading.

Home example: Filtering expenses in the database before loading.

Nigerian example: Filtering election results in the database before loading.

How to do it: Use native database queries or ensure steps are foldable.

Illustration:

No Query Folding: Load all data, then filter.
Query Folding: Filter at the database, then load.

Mini summary: Query folding uses the database for faster processing.

Lesson 5: Optimize Data Types

Definition: Use the most efficient data type for each column.

Why important: The wrong data type can slow down processing.

Simple explanation: It's like using the right tool for the job.

Real-life example: Use Integer instead of Text for numeric columns.

School example: Use Date type for dates, not Text.

Home example: Use Number for amounts, not Text.

Nigerian example: Use Integer for population, not Text.

How to do it: Change data types to the most efficient.

Illustration:

Text: "100" → 3 bytes
Integer: 100 → 4 bytes (actually more efficient for calculations)

Mini summary: Use efficient data types.

Lesson 6: Avoid Expensive Operations

Definition: Some operations are slow (e.g., merging large tables). Avoid them if possible.

Why important: Expensive operations can make your query very slow.

Simple explanation: It's like taking the long way home instead of the shortcut.

Real-life example: Avoid merging very large tables if you can.

School example: Avoid complex joins on large student tables.

Home example: Avoid merging huge budget files.

Nigerian example: Avoid merging massive election datasets.

How to do it: Filter before merging, use smaller tables.

Illustration:

Expensive: Merge 1M rows with 1M rows.
Better: Filter both to 10K rows, then merge.

Mini summary: Avoid slow operations when possible.

Lesson 7: Incremental Refresh

Definition: Incremental refresh loads only new or changed data.

Why important: Saves time and resources for large datasets.

Simple explanation: Instead of reading the whole book, you only read new pages.

Real-life example: A company with 5 years of sales data only loads the last 3 months.

School example: A teacher only loads the latest test scores.

Home example: You only load this month's expenses.

Nigerian example: A bank only loads transactions from the last 7 days.

How to do it: In Power BI, set up incremental refresh policies.

Illustration:

Incremental Refresh:
   Load last 3 months
   Refresh daily

Mini summary: Incremental refresh loads only new data.

Lesson 8: Optimize DAX Measures

Definition: Write DAX measures efficiently to avoid slow calculations.

Why important: Slow DAX slows down the entire report.

Simple explanation: It's like using a fast calculator instead of counting on your fingers.

Real-life example: Use CALCULATE with simple filters instead of complex FILTER.

School example: Use simple SUM instead of complex calculations.

Home example: Use simple totals instead of complex conditions.

Nigerian example: Use simple aggregations instead of complex logic.

Tips: Use VAR, avoid nested CALCULATE, use efficient functions.

Illustration:

Slow: CALCULATE(SUM(Sales), FILTER(All(Sales), Sales[Year] = 2025))
Fast: CALCULATE(SUM(Sales), Sales[Year] = 2025)

Mini summary: Optimize DAX for speed.

Lesson 9: Use Performance Analyzer

Definition: Performance Analyzer is a tool in Power BI that shows how long each part of a report takes to load.

Why important: It helps you find bottlenecks.

Simple explanation: It's like a timer that tells you where time is being wasted.

Real-life example: Use Performance Analyzer to see which visual is slow.

School example: Use it to see which calculation is slow.

Home example: Use it to see which chart takes time.

Nigerian example: Use it to see which part of the dashboard is slow.

How to do it: In Power BI, go to View → Performance Analyzer.

Illustration:

Performance Analyzer:
   Visual 1: 1 second
   Visual 2: 0.5 seconds
   Visual 3: 10 seconds ← slow!

Mini summary: Performance Analyzer finds slow parts.

Lesson 10: Use Variables in DAX

Definition: Variables (VAR) store values for reuse, making DAX faster.

Why important: Variables avoid recalculating the same thing multiple times.

Simple explanation: It's like storing a number in your memory to use later.

Real-life example: VAR TotalSales = SUM(Sales[Amount]); RETURN TotalSales * 0.1.

School example: VAR TotalMarks = SUM(Grades[Score]); RETURN TotalMarks / 100.

Home example: VAR TotalExpenses = SUM(Budget[Amount]); RETURN TotalExpenses * 0.2.

Nigerian example: VAR TotalVotes = SUM(Votes[Count]); RETURN TotalVotes / 10000.

How to write: VAR name = expression RETURN expression.

Illustration:

Without VAR: CALCULATE(SUM(Sales), Sales[Year]=2025) is calculated multiple times.
With VAR: VAR YearSales = CALCULATE(SUM(Sales), Sales[Year]=2025) RETURN YearSales * 2.

Mini summary: VAR makes DAX faster and cleaner.

Lesson 11: Avoid Calculated Columns

Definition: Calculated columns are evaluated row by row, which is slow.

Why important: Measures are faster than calculated columns.

Simple explanation: It's like doing work row by row vs doing it all at once.

Real-life example: Use measures instead of calculated columns when possible.

School example: Use measures for averages, not calculated columns.

Home example: Use measures for totals, not calculated columns.

Nigerian example: Use measures for aggregations, not calculated columns.

How to do it: Use measures instead of calculated columns for aggregations.

Illustration:

Calculated Column: [Profit] = [Sales] - [Cost] (row by row)
Measure: Total Profit = SUM(Sales) - SUM(Cost) (dynamic)

Mini summary: Use measures instead of calculated columns.

Lesson 12: Use Star Schema

Definition: A star schema with fact and dimension tables is faster for reporting.

Why important: Star schemas are optimized for Power BI.

Simple explanation: It's like having a well-organized library.

Real-life example: Fact table: Sales. Dimensions: Products, Customers, Time.

School example: Fact table: Grades. Dimensions: Students, Subjects.

Home example: Fact table: Expenses. Dimensions: Categories, Months.

Nigerian example: Fact table: Votes. Dimensions: Parties, States.

How to do it: Build a star schema with one fact and many dimensions.

Illustration:

        +----------+
        | Products |
        +----------+
             |
+----------+----------+----------+
| Customers|──│ Sales   │──│ Time   |
+----------+----------+----------+
             |
        +----------+
        | Regions  |
        +----------+

Mini summary: Star schemas are fast and efficient.

Lesson 13: Use DirectQuery vs Import

Definition: Import loads data into Power BI. DirectQuery queries the data source live.

Why important: Import is faster for reporting, but requires storage. DirectQuery is slower but always up-to-date.

Simple explanation: Import is like having a copy of the book. DirectQuery is like reading the book online.

Real-life example: Use Import for fast reports, DirectQuery for live data.

School example: Use Import for historical grades, DirectQuery for current grades.

Home example: Use Import for budget, DirectQuery for bank transactions.

Nigerian example: Use Import for election results, DirectQuery for live updates.

How to choose: Use Import when possible. Use DirectQuery when you need live data.

Illustration:

Import: Fast, but data is copied.
DirectQuery: Slower, but data is always current.

Mini summary: Choose Import for speed, DirectQuery for live data.

Lesson 14: Monitor and Tune

Definition: Continuously monitor performance and make adjustments.

Why important: Performance can degrade over time.

Simple explanation: It's like checking your car's engine regularly.

Real-life example: Check refresh times and optimize.

School example: Check report load times and optimize.

Home example: Check budget update times and optimize.

Nigerian example: Check dashboard load times and optimize.

How to do it: Use Performance Analyzer, check refresh times, and make improvements.

Illustration:

Monitor: Refresh time = 10 minutes
Tune: Optimize query → Refresh time = 2 minutes

Mini summary: Monitor and tune for ongoing performance.

Lesson 15: Performance Best Practices Summary

Definition: Key practices to keep your reports fast.

Why important: Following best practices ensures consistent performance.

Simple explanation: It's like following a recipe for a perfect cake every time.

  • Load only necessary data (columns and rows).
  • Use query folding when possible.
  • Use efficient data types.
  • Use measures instead of calculated columns.
  • Build a star schema.
  • Use incremental refresh for large datasets.
  • Optimize DAX with VAR and simple filters.
  • Monitor performance regularly.

Illustration:

1. Load only what you need.
2. Use query folding.
3. Use efficient data types.
4. Use measures.
5. Build star schema.
6. Use incremental refresh.
7. Optimize DAX.
8. Monitor performance.

Mini summary: Follow best practices for optimal performance.

📖 Key Vocabulary (with simple definitions)

  • Performance: How fast your data loads and refreshes.
  • Query Folding: Pushing operations to the database.
  • Incremental Refresh: Loading only new data.
  • Performance Analyzer: A tool to measure performance.
  • Star Schema: A data model with one fact and many dimensions.
  • DirectQuery: Querying live data source.
  • Import: Copying data into Power BI.
  • Optimization: Making something faster and more efficient.

🧠 Important Concepts

  • Performance is crucial for a good user experience.
  • Load only what you need.
  • Use query folding to leverage database power.
  • Star schemas are optimized for performance.
  • Incremental refresh saves time.
  • Monitor performance regularly.

🔢 Step-by-Step Explanations

How to Use Performance Analyzer:

  1. Open Power BI Desktop.
  2. Go to View → Performance Analyzer.
  3. Click "Start Recording".
  4. Interact with your report.
  5. Stop recording and see the time for each visual.
  6. Identify slow visuals and optimize them.

How to Set Up Incremental Refresh:

  1. In Power BI Desktop, go to the table.
  2. Click "Manage Table" → "Incremental Refresh".
  3. Set the refresh policy (e.g., load last 3 months).
  4. Publish to Power BI Service.
  5. Set up scheduled refresh.

🌍 Real-life Examples

  • Retail: Optimize sales reports by loading only current year data and using incremental refresh.
  • Healthcare: Use query folding to filter patient data at the database.
  • Finance: Use star schemas for fast financial reporting.

🇳🇬 Nigerian Examples

  • Election: Use incremental refresh for live election results.
  • Agriculture: Use query folding to filter crop data by state.
  • Telecom: Use star schemas for fast call volume analysis.

🎈 Fun Examples Children Can Relate To

  • Toys: Optimize a toy inventory by loading only this year's toys.
  • Candy: Use incremental refresh to load only new candy sales.
  • Games: Use query folding to filter game scores by player.

🏠 Everyday Examples

  • Budget: Load only this month's expenses.
  • Chores: Load only today's chores.
  • School: Load only current semester grades.

👩‍🏫 Teacher Notes

  • Emphasize that performance is about making things faster.
  • Use real-world examples to show the impact of optimization.
  • Encourage students to use Performance Analyzer.

👨‍👩‍👦 Parent Tips

  • Help your child optimize a simple report by removing unnecessary columns.
  • Discuss how optimization saves time in everyday life.

💡 Interesting Facts

  • Optimization can make reports 10 times faster.
  • Query folding is one of the most powerful optimization techniques.
  • Performance Analyzer was introduced in Power BI in 2020.

❓ Did You Know?

Did you know that Power BI has a "Performance Analyzer" that can tell you exactly how long each visual takes to load? It's like a stopwatch for your reports!

🔔 Remember This

  • Load only what you need.
  • Use query folding.
  • Use efficient data types.
  • Use measures instead of calculated columns.
  • Build a star schema.
  • Use incremental refresh.
  • Monitor performance regularly.

⚠️ Common Mistakes

  • Loading too much data – slows down everything.
  • Not using query folding – misses database optimization.
  • Using calculated columns for aggregations – slow.
  • Ignoring performance – reports become slow over time.

✅ Best Practices

  • Always load only necessary data.
  • Use query folding whenever possible.
  • Use efficient data types.
  • Use measures for aggregations.
  • Build star schemas.
  • Use incremental refresh for large datasets.
  • Monitor performance with Performance Analyzer.

📊 ASCII Illustrations

Performance Optimization Flow

   Start
     |
     V
 Load Data (only what you need)
     |
     V
 Use Query Folding (if possible)
     |
     V
 Use Efficient Data Types
     |
     V
 Use Measures (not calculated columns)
     |
     V
 Build Star Schema
     |
     V
 Use Incremental Refresh
     |
     V
 Monitor Performance
     |
     V
   Done 🎉

Star Schema

        +----------+
        | Products |
        +----------+
             |
+----------+----------+----------+
| Customers|──│ Sales   │──│ Time   |
+----------+----------+----------+
             |
        +----------+
        | Regions  |
        +----------+

📋 Comparison Tables

Import vs DirectQuery

FeatureImportDirectQuery
SpeedFastSlower
Data freshnessDepends on refreshAlways live
StorageRequires storageNo storage
Best forReportingLive data

Calculated Column vs Measure

FeatureCalculated ColumnMeasure
SpeedSlowerFaster
StorageUses storageNo storage
EvaluationRow by rowOn the fly
Best forRow-level calculationsAggregations

📝 End-of-Module Summary

Congratulations! You have completed Module Sixteen on Performance Optimization. You learned:

  • Why performance matters.
  • How to load only necessary data.
  • How to use query folding.
  • How to optimize data types.
  • How to use measures instead of calculated columns.
  • How to build star schemas.
  • How to use incremental refresh.
  • How to monitor performance with Performance Analyzer.

You now have the skills to make your Power Query and Power BI solutions fast and efficient!

❓ Frequently Asked Questions (10)

  1. Why is performance important? – It saves time and improves user experience.
  2. What is query folding? – Pushing operations to the database.
  3. What is incremental refresh? – Loading only new data.
  4. What is a star schema? – A data model with one fact and many dimensions.
  5. What is the difference between Import and DirectQuery? – Import copies data, DirectQuery queries live.
  6. What is Performance Analyzer? – A tool to measure load times.
  7. Why use measures instead of calculated columns? – Measures are faster.
  8. What is the best data type for numbers? – Integer or Decimal.
  9. How can I reduce data load? – Filter and remove unnecessary columns.
  10. What is the most important performance tip? – Load only what you need.

📝 Review Questions (15)

  1. Why does performance matter?
  2. What is query folding?
  3. What is incremental refresh?
  4. What is a star schema?
  5. What is the difference between Import and DirectQuery?
  6. What is Performance Analyzer?
  7. Why use measures instead of calculated columns?
  8. What is the best data type for numbers?
  9. How can you reduce data load?
  10. What is the most important performance tip?
  11. How do you set up incremental refresh?
  12. What is a bottleneck?
  13. How can you optimize DAX?
  14. Why is a star schema efficient?
  15. What is the first step in performance optimization?

✍️ Fill-in-the-Blank Exercises

  1. ______ is how fast your data loads and refreshes.
  2. ______ pushes operations to the database.
  3. ______ loads only new data.
  4. A ______ schema has one fact and many dimensions.
  5. ______ is a tool to measure load times.

✅ True or False Exercises

  1. Performance is not important. (False)
  2. Query folding makes queries faster. (True)
  3. Incremental refresh loads all data. (False)
  4. A star schema is efficient. (True)
  5. Import is slower than DirectQuery. (False)

🔘 Multiple Choice Questions (15 with answers)

  1. What is query folding?
    a) Pushing operations to the database b) Loading all data c) Using DAX d) Using calculated columns
    Answer: a
  2. What is incremental refresh?
    a) Loading only new data b) Loading all data c) Loading no data d) Deleting data
    Answer: a
  3. What is a star schema?
    a) One fact, many dimensions b) Many facts, one dimension c) No facts d) No dimensions
    Answer: a
  4. What is Performance Analyzer?
    a) A tool to measure load times b) A tool to delete data c) A tool to add data d) A tool to sort data
    Answer: a
  5. Why use measures instead of calculated columns?
    a) They are faster b) They are slower c) They are not used d) They are static
    Answer: a
  6. What is the best data type for numbers?
    a) Integer b) Text c) Date d) Boolean
    Answer: a
  7. How can you reduce data load?
    a) Filter and remove columns b) Add more columns c) Add more rows d) Do nothing
    Answer: a
  8. What is the most important performance tip?
    a) Load only what you need b) Load everything c) Use calculated columns d) Use DirectQuery
    Answer: a
  9. What is DirectQuery?
    a) Querying live data b) Loading all data c) Copying data d) Deleting data
    Answer: a
  10. What is Import?
    a) Copying data into Power BI b) Querying live data c) Deleting data d) Sorting data
    Answer: a
  11. What is a bottleneck?
    a) A slow part b) A fast part c) A new part d) A deleted part
    Answer: a
  12. How can you optimize DAX?
    a) Use VAR b) Use complex formulas c) Use calculated columns d) Use DirectQuery
    Answer: a
  13. Why is a star schema efficient?
    a) It optimizes joins b) It is simple c) It is complex d) It is slow
    Answer: a
  14. What is the first step in performance optimization?
    a) Load only what you need b) Load everything c) Use DirectQuery d) Use calculated columns
    Answer: a
  15. What is the purpose of Performance Analyzer?
    a) To find slow parts b) To delete data c) To add data d) To sort data
    Answer: a

🔗 Matching Exercises

Match the term to its description:

TermDescription
1. Query FoldingA. Loading only new data
2. Incremental RefreshB. Pushing operations to the database
3. Star SchemaC. One fact, many dimensions
4. Performance AnalyzerD. Tool to measure load times

Answers: 1-B, 2-A, 3-C, 4-D

✍️ Short Answer Questions

  1. What is query folding and why is it important?
  2. Explain incremental refresh.
  3. What is a star schema and why is it efficient?
  4. How do you use Performance Analyzer?
  5. What are the top three performance tips?

📖 Scenario-based Exercises

Scenario 1: You have a report that takes 10 minutes to refresh. How would you optimize it? List three steps.

Scenario 2: Your report has a slow visual. How would you find the cause and fix it?

👥 Group Activity

In groups, take a slow report and optimize it. Use Performance Analyzer to identify bottlenecks, reduce data load, and apply optimizations. Present the before and after results.

🧑‍🎓 Individual Activity

Load a dataset into Power Query. Apply performance optimizations: remove unnecessary columns, use query folding if possible, and optimize data types. Measure the improvement.

💬 Classroom Discussion Questions

  • Why is performance often overlooked?
  • What is the biggest performance challenge you've faced?
  • How can performance optimization improve user experience?

🛠️ Mini Project

Project: Optimize a Sales Dashboard

You have a sales dashboard that is slow. Apply performance optimization techniques: reduce data load, use query folding, build a star schema, use incremental refresh, and optimize DAX. Show the improvement in load time.

📋 Practical Assignment

Download a large dataset. Build a report and apply performance optimizations. Use Performance Analyzer to measure load times before and after. Document your optimization steps.

🏆 Challenge Exercise

Take a dataset with 10 million rows. Apply query folding, incremental refresh, and star schema. Optimize DAX measures. Aim for a refresh time under 2 minutes.

📝 Quiz Answers

Fill-in-the-Blank: 1. Performance, 2. Query folding, 3. Incremental refresh, 4. star, 5. Performance Analyzer

True/False: 1-F, 2-T, 3-F, 4-T, 5-F

Matching: 1-B, 2-A, 3-C, 4-D

🔑 Key Takeaways

  • Performance matters because time is valuable.
  • Load only what you need.
  • Use query folding to leverage the database.
  • Use efficient data types.
  • Use measures instead of calculated columns.
  • Build a star schema.
  • Use incremental refresh for large datasets.
  • Monitor performance with Performance Analyzer.

📖 Preparation for the Next Module

In Module Seventeen, we will learn about Power Query for Data Analysis Expert – Capstone. You will apply everything you've learned to a real-world project. You will build a complete data pipeline from start to finish. Get ready to showcase your skills!

Before the next class, review all modules and practice performance optimization on a sample dataset.


© 2025 Certified Power Query for Data Analysis Expert – Module Sixteen

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it — ₦4,000/month.

🎓 Sign Up & Unlock for ₦4,000/month
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
→