Power Query in Power BI: Clean and Shape Data Before It Reaches the Model

8 min read

Power Query is the data preparation layer inside Power BI Desktop: you open it with Home, Transform data, and every cleaning step you take there is recorded and replayed automatically on each refresh. It connects to a source, filters, reshapes and combines tables, and only the finished result loads into the model where DAX and visuals take over. In Power BI the two things that matter most are which steps run at the database (query folding) and which queries load into the model at all.

Power Query is the same engine in Excel and Power BI. Our lesson on Power Query in Excel covers the editor basics, combining files from a folder and unpivoting in detail, and this one does not repeat them. It covers what changes once your data comes from a database and ends up in a published Power BI model.

Where Power Query sits in Power BI

Data moves through Power BI in a fixed order: source, Power Query, model, report. Power Query is the only stage where rows are removed or reshaped; after Close and Apply, the model holds whatever Power Query produced.

Task Click path in Power BI Desktop
Open the editor Home ribbon, Transform data
Connect to a new source from inside the editor Home ribbon, New Source
See every step of a query Query Settings pane on the right, Applied Steps
See the M code for a query Home ribbon, Advanced Editor
Check data quality View ribbon, tick Column quality, Column distribution and Column profile
See how queries feed each other View ribbon, Query Dependencies
Commit and load Home ribbon, Close and Apply

What changes from Excel to Power BI

Power Query in Excel Power Query in Power BI
Where results go A worksheet table, a PivotTable or the Data Model Always the Power BI model, unless you switch loading off
Typical source Files and folders Databases as often as files
Query folding Rarely matters Decides whether refresh takes seconds or an hour
Parameters Possible, rarely used Used for server names and incremental refresh
Refresh after sharing Someone opens the workbook and clicks Refresh The Power BI Service runs it on a schedule, through a gateway if the source is on premises
Shared logic Copy the query to another workbook Dataflows in the Service let several models reuse one set of steps

The data used throughout

An Ahmedabad pharmaceutical distributor supplies stockists across Gujarat. The sales head wants monthly sales against target by district. There are three sources.

invoices, a table in the company’s SQL Server database (only eight rows shown; the real table has several lakh):

invoice_no invoice_date stockist_code amount
INV-5101 2026-04-03 ST01 42500
INV-5102 2026-04-11 ST02 18200
INV-5103 2026-04-25 ST03 27900
INV-5104 2026-05-06 ST01 39800
INV-5105 2026-05-14 ST04 22600
INV-5106 2026-05-29 ST02 16400
INV-5107 2026-06-09 ST03 31200
INV-5108 2026-06-21 ST04 25300

stockists, an Excel sheet kept by the sales team, with the kind of mess that sheets accumulate:

stockist_code stockist_name district
ST01 Sabarmati Medical Agencies Ahmedabad
ST02 Maninagar Pharma ahmedabad
ST03 Alkapuri Medicos Vadodara
ST04 Varachha Distributors Surat

targets, an Excel sheet from finance, one column per month:

district Apr 2026 May 2026 Jun 2026
Ahmedabad 60000 55000 50000
Vadodara 25000 25000 30000
Surat 20000 22000 24000

Step 1: Connect to SQL Server and keep the query folding

Home ribbon, Get data, SQL Server. Enter the server and database, and choose a Data Connectivity mode. Import copies the data into the model and is the right default. DirectQuery leaves it in the database and queries it each time a visual loads, which suits very large or near-real-time data at the cost of speed and DAX restrictions.

Then shape the invoices query in this order:

Step Click path Folds to SQL Server
Keep only this financial year Filter arrow on invoice_date, Date Filters, After or Equal, 01-04-2026 Yes
Remove unneeded columns Home ribbon, Choose Columns Yes
Add a month column Select invoice_date, Add Column ribbon, Date, Month, Start of Month Yes
Total by stockist and month Home ribbon, Group By, Advanced, group on stockist_code and Start of Month, Sum of amount Yes

Query folding means Power Query translates your steps into one SQL query and lets the database do the work. Filtering several lakh rows at the server and receiving a few hundred grouped rows is far faster than downloading every invoice and filtering on your laptop. To check, right-click the last step in Applied Steps: if View Native Query is available, the query still folds, and you can read the SQL it sends. Applied Steps also shows a small indicator beside each step saying whether it folds.

Folding stops at the first step the source cannot translate, and every step after that runs in Power BI. Some steps never fold against SQL Server, such as adding an index column or merging with an Excel file. So order matters: do the filtering, column removal and grouping first, while folding still holds, and anything that breaks folding last.

Step 2: Profile the columns before you clean

Open the stockists query and switch on the View ribbon’s three profiling options. Under each column header you now see the share of valid, error and empty values, a mini histogram, and the count of distinct and unique values. Select the district column and Column profile shows 4 distinct values where the sales head expects 3, because it counts “Ahmedabad” and “ahmedabad” separately.

One setting matters: by default profiling reads only the first 1,000 rows. Click “Column profiling based on top 1000 rows” in the status bar at the bottom and switch it to the entire data set before trusting the counts on a large table.

Step 3: Clean the stockist list

Fix Click path M function it writes
Remove stray spaces Select district, Transform ribbon, Format, Trim Table.TransformColumns with Text.Trim
Standardise case Transform ribbon, Format, Capitalize Each Word Table.TransformColumns with Text.Proper
Fix a known misspelling Transform ribbon, Replace Values Table.ReplaceValue
Set types Click the type icon on each column header Table.TransformColumnTypes

Power Query is case-sensitive in comparisons and merges, unlike Excel formulas, so “ahmedabad” and “Ahmedabad” would become two districts in every visual. Standardising case here fixes it once, for every refresh.

Step 4: Combine the three sources

Bring district into invoices. In the invoices query, Home ribbon, Merge Queries, choose stockists, match on stockist_code, Join Kind Left Outer. Expand the new column and tick only district. This merge crosses from SQL Server to Excel, so folding ends here, which is why the grouping happened first.

Total by district and month. Group By again, on district and Start of Month. The result:

district Month Actual
Ahmedabad Apr 2026 60700
Ahmedabad May 2026 56200
Vadodara Apr 2026 27900
Vadodara Jun 2026 31200
Surat May 2026 22600
Surat Jun 2026 25300

Reshape targets. Select the district column, Transform ribbon, Unpivot Columns dropdown, Unpivot Other Columns, rename the result to Month and Target, then change Month’s type to Date. The Excel lesson walks through this step in detail.

Merge actuals onto targets. Start from targets, Merge Queries with the district actuals on district and Month, Join Kind Left Outer, and expand Actual. Starting from targets matters: a month with a target and no sales still appears, with Actual as null. Replace null with 0 using Transform ribbon, Replace Values.

Load that table, and a DAX measure, Achievement = DIVIDE(SUM(sales_vs_target[Actual]), SUM(sales_vs_target[Target])), returns:

district Month Target Actual Achievement
Ahmedabad Apr 2026 60000 60700 101.2%
Ahmedabad May 2026 55000 56200 102.2%
Ahmedabad Jun 2026 50000 0 0.0%
Vadodara Apr 2026 25000 27900 111.6%
Vadodara May 2026 25000 0 0.0%
Vadodara Jun 2026 30000 31200 104.0%

Surat shows 0.0% in April, then 102.7% in May and 105.4% in June. Had the merge started from actuals, the three zero months would have vanished, and the sales head would never have seen them. Keep the ratio as a DAX measure rather than a Power Query column, so that a quarter’s achievement is computed from the quarter’s totals and not averaged from the months.

Step 5: Decide what loads into the model

Every query loads into the model by default, and that is usually wrong. The stockists, targets and grouped invoices queries were steps on the way; only the final table and real lookup tables belong in the model.

Setting Where Use it for
Enable load Right-click a query in the Queries pane, untick Enable load Staging queries; the name turns italic and nothing loads
Include in report refresh Same right-click menu A static table you do not want refreshed
Reference Right-click a query, Reference A new query that starts from another’s output, so a shared cleaning step lives in one place
Duplicate Right-click a query, Duplicate A full independent copy of every step, for when the two will diverge

Reference is the one to reach for. If invoices feeds two tables, reference it twice; fix a step once, and both follow. Duplicate copies the bug along with the steps.

Parameters: the server name and incremental refresh

Home ribbon, Manage Parameters, New Parameter. Create ServerName as Text, then edit the source step to use it: Sql.Database(ServerName, “sales”). Moving from a test server to production then means changing one value, and after publishing, the parameter can be edited in the Service under the semantic model’s settings.

Two parameters are special. Create RangeStart and RangeEnd, both of type Date/Time, filter invoice_date between them, and you can then set incremental refresh: right-click the invoices table in Desktop’s Data pane, Incremental refresh, and choose how many years to keep and how many recent days to refresh. The Service then reloads only recent rows each night instead of the whole table. It works on Pro as well as Premium, and it relies on the filter folding to the source.

M, briefly

Every click writes a line of M, Power Query’s formula language. You rarely need to type it, but reading it helps when a step fails. A query is a single let expression: each step is a named variable built from the step before, and in returns the last one. Step names with spaces are written as #”Changed Type”. M is case-sensitive, so Text.Trim works and text.trim does not.

Step in this lesson M it produces (simplified)
Connect Source = Sql.Database(ServerName, “sales”)
Filter dates Table.SelectRows(dbo_invoices, each [invoice_date] >= #date(2026, 4, 1))
Month column Table.AddColumn(#”Removed Other Columns”, “Start of Month”, each Date.StartOfMonth([invoice_date]))
Group Table.Group(#”Inserted Start of Month”, {“stockist_code”, “Start of Month”}, {{“amount”, each List.Sum([amount]), type number}})
Merge Table.NestedJoin(#”Grouped Rows”, {“stockist_code”}, stockists, {“stockist_code”}, “stockists”, JoinKind.LeftOuter)
Unpivot Table.UnpivotOtherColumns(Source, {“district”}, “Month”, “Target”)
Replace null Table.ReplaceValue(#”Expanded actuals”, null, 0, Replacer.ReplaceValue, {“Actual”})

The word each is shorthand for a function applied to every row, and [amount] means that row’s amount. Read the Group line as: group by these two columns, and make a column called amount that sums each group’s amounts.

After publishing: refresh in the Service

Once the report is published, the Power BI Service runs these queries on a schedule. The SQL Server here sits in the distributor’s office, so refresh needs the on-premises data gateway installed on a machine that can reach the server, and the Excel files must be somewhere the gateway can see, ideally SharePoint or OneDrive rather than someone’s desktop. If several reports need the same cleaned stockist list, move that query into a dataflow in the Service, so one copy of the logic feeds them all.

Mistakes that break refresh or slow it down

Breaking folding early. An index column or Excel merge in step two forces every later step to run on your machine against every row. Keep folding steps first.

Hard-coded file paths. A targets file in someone’s Downloads folder works on their laptop and nowhere else, including the gateway. Keep source files on SharePoint or a shared drive the gateway can reach, and use a parameter for the path.

Loading staging queries. Each one adds a table to the model, its own refresh time and a confusing name in the Data pane. Untick Enable load.

Trusting the automatic Changed Type step. Power Query guesses types from the first rows and hard-codes column names in that step. A renamed column at source then breaks refresh. Delete the automatic step and set types yourself, after the columns are final.

Doing in DAX what belongs here. Trimming text or splitting columns with DAX calculated columns makes the model bigger and slower. Shape once in Power Query; calculate in DAX.

Frequently asked questions

What is Power Query in Power BI?

Power Query is the data preparation tool inside Power BI Desktop, opened with Home, Transform data. It connects to sources, cleans and reshapes data, and records each step so it replays on every refresh. Only its output loads into the model, where DAX measures and visuals work with it.

What is the difference between Power Query and DAX?

Power Query shapes data before it loads: removing rows, fixing text, merging tables, unpivoting. DAX calculates on the loaded model: totals, ratios and time comparisons that respond to a reader’s filters. Use Power Query for anything done once per refresh, and DAX for anything that must change when someone clicks a slicer.

What is query folding in Power BI?

Query folding is Power Query translating your steps into a query the source runs itself, such as one SQL statement against a database. It lets the database filter and group millions of rows and send back only the result, which makes refresh much faster. Right-click a step and check whether View Native Query is available to see if it still folds.

Do I need to learn M for Power BI?

Not to start. Almost every step can be done by clicking, and Power Query writes the M for you. Reading M becomes useful when a refresh fails, when you need a parameter in a source step, or for a transformation no button offers. Writing it from scratch is a skill for later.

Is Power Query in Power BI the same as in Excel?

The engine, the editor and the M language are the same, so skills carry over directly. Power BI differs in where the results go, always into its model, and in what matters most: query folding against databases, parameters, incremental refresh and scheduled refresh in the Power BI Service.

Why is my Power Query refresh so slow?

Usually because folding broke early and Power BI is downloading every row to process locally, or because many staging queries are loading into the model. Move filters and column removal to the top, check View Native Query on the last step, untick Enable load on intermediate queries, and remove columns you do not use.

Where this fits in the bigger picture

Power Query does the unglamorous part of a report, and a good share of analyst interviews probe exactly that. Our Power BI tutorial shows where it sits in a full build, and our Power BI interview questions include the folding and Merge versus Append questions. Merges are joins by another name, so our SQL joins lesson explains the join kinds well.

SkilloVilla’s Data Analytics with Python track includes a Data Visualization in Power BI module on visualisation and dashboarding, alongside Excel, SQL and Python, with live classes, mentorship from working analysts and placement support.

Power BI Projects for Your Portfolio: 8 Ideas Using…

Power BI projects for a data analyst portfolio, built on Indian public data: the dataset, the question, the visuals and what each one shows...
SkilloVilla Team
7 min read

DAX in Power BI: How It Works, With Worked…

DAX in Power BI explained: filter context, CALCULATE, iterators like SUMX, time intelligence for an April to March year, and checked worked examples.
SkilloVilla Team
7 min read

Power BI Service Explained: Workspaces, Sharing, Refresh and Licences

Power BI Service explained: how it differs from Desktop, workspaces, publishing, sharing, apps, scheduled refresh, gateways and which licence you need.
SkilloVilla Team
7 min read

Leave a Reply