Sub topic 14
Organizing Queries: References, Staging Queries, and Parameters
This chapter assumes you can connect Power BI Desktop to a CSV or Excel file and that you have used the Applied Steps pane. It also assumes you know how to promote headers, set data types, and clean text. Here you will learn how to keep a growing set of queries readable, avoid repeating work, and make source locations easy to change.
Why organization matters
A single query is easy to manage. A real report often has a dozen queries. Several of them may start from the same file and repeat the same cleaning steps. If you copy those steps into each query, one fix has to be made many times, and the copies drift apart.
Three tools address this:
- A reference is a new query that starts from the output of an existing query.
- A staging query is a query that does the shared cleaning once and is not loaded into the model. Other queries build on it.
- A parameter is a named value, such as a folder path, that queries can read. You change it in one place.
Duplicate versus reference
Right-click a query in the Queries pane and you will see both Duplicate and Reference. They look similar but behave differently.
| Option | What it creates | Effect of changing the original |
|---|---|---|
| Duplicate | A full copy of the M code, with its own source step | None. The copy is independent. |
| Reference | A new query whose first step points at the original query | The new query sees the change when it refreshes. |
Use Duplicate when you want a starting point that will diverge. Use Reference when the new query should always depend on the cleaned output of another.
The M code for a reference is short. If the original query is named SalesStaging, the new query looks like this:
let
Source = SalesStaging
in
SourceThe Source step holds the whole table that SalesStaging returns. You then add your own steps after it.
The staging pattern
In a staging design, one query connects to the source and applies the cleaning every consumer needs. Other queries reference it and shape the data for a specific purpose.
For example, suppose sales.csv feeds both a fact table of orders and a small table of customers. Build it in three queries:
SalesStagingloads the file, promotes headers, sets types, trims text, and removes duplicates.OrdersreferencesSalesStagingand keeps the order columns.CustomersreferencesSalesStaging, keeps the customer columns, and removes duplicate customers.
The next diagram shows the dependency.
Here is a staging query and a query that references it. The staging query uses the #table constructor, so you can paste it into a blank query and run it.
let
Source = #table(
{"Customer", "Region", "Amount"},
{
{" alice smith ", "West", 120},
{"BOB JONES", "East", 80},
{"BOB JONES", "East", 80}
}
),
CleanedText = Table.TransformColumns(Source, {{"Customer", each Text.Proper(Text.Trim(_)), type text}}),
RemovedDuplicates = Table.Distinct(CleanedText)
in
RemovedDuplicatesName this query SalesStaging. In a second query, reference it and keep only the customer columns:
let
Source = SalesStaging,
CustomerColumns = Table.SelectColumns(Source, {"Customer", "Region"}),
DistinctCustomers = Table.Distinct(CustomerColumns)
in
DistinctCustomersIf you later discover that names need another cleaning step, you add it to SalesStaging once. Both downstream queries pick it up.
Disable the load for staging queries
By default every query is loaded into the model. A staging query is usually an intermediate result, so loading it adds a table nobody needs and uses memory.
To stop that, right-click the query and clear Enable load. The query name turns italic in the Queries pane. The query still runs when other queries need it. It just does not appear as a table in the model.
Organizing with groups and names
Once you have several queries, use the Queries pane to keep them findable.
- Right-click in the pane and choose New Group to create a folder. Common groups are
Staging,Dimensions,Facts, andParameters. - Give queries names that say what they are.
SalesStagingis better thanQuery1orsales. - Rename steps in the Applied Steps pane when the default name is unclear. Press F2 on a step to rename it. A step called
Removed rows with old test ordersis easier to read thanFiltered Rows.
Query names become table names in the model, and they appear in DAX and in report field lists. Choose them with that in mind, and rename queries before you build measures that use them. Renaming later can break references in other places, such as report visuals.
Parameters
A parameter stores a value that queries can reuse. The most common use is a file path or server name.
To create one, choose Home > Manage Parameters > New Parameter. Fill in these fields:
- Name, for example
SourceFolder. - Type, such as Text, Decimal Number, or Date.
- Suggested Values, either Any value or a list of allowed values.
- Current Value, for example
C:\Data.
The parameter appears in the Queries pane as its own query. Its M code is a single value with metadata:
"C:\Data" meta [IsParameterQuery = true, Type = "Text", IsParameterQueryRequired = true]Using a parameter in a source step
You can use the parameter in the formula bar or Advanced Editor. Replace the hard-coded path in the load step so that the folder comes from SourceFolder:
let
Source = Csv.Document(File.Contents(SourceFolder & "\sales.csv"), [Delimiter = ",", Encoding = 65001]),
PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars = true])
in
PromotedHeadersThe & operator joins two text values. When a colleague opens the file on a different machine, they change SourceFolder once instead of editing every query that reads from that folder.
You can change the current value later with Home > Manage Parameters, or from Power BI Desktop with Transform data > Edit parameters.
Other uses for parameters
- A cutoff date that filters rows, such as keeping orders after
StartDate. - A threshold used in a conditional column.
- A switch such as a development row limit. You might keep only the top 1000 rows while building, then raise the limit.
Common errors
Changing the referenced query breaks the downstream query. A reference reads its input by column name. If you rename or remove a column in SalesStaging, a later step in Orders that uses that name fails with an error such as The column 'Amount' of the table wasn't found. Fix it by updating the step in the downstream query, or avoid removing columns in staging that others need.
Duplicating when you meant to reference. After a Duplicate, a fix to the original does not reach the copy. If you see the same bug in two queries, check whether one was duplicated.
Loading the staging query by accident. If your model has a table that looks like a half-cleaned copy of another, Enable load is probably still on. Clear it on the staging query.
Source evaluated more than once. When several queries reference a staging query, Power Query can read the source separately for each one during a refresh. For a large file this slows the refresh. Keep the staging query light, and filter early.
Parameter type mismatch. If SourceFolder is set to type Number, joining it with & to text fails. Set the type to Text when the value is a path.
Circular references. Query A cannot depend on query B if B depends on A. The editor reports a cycle error. Restructure so that dependencies flow one way, from staging to outputs.
Checking dependencies
Choose View > Query Dependencies to see a diagram of how your queries connect. It shows each source, each staging query, and each output. Use it to confirm that the structure matches your plan and to find queries that nothing uses.
Decision guide
| Situation | Choice |
|---|---|
| Several tables come from one source and share cleaning | Staging query plus references |
| You want to try a different approach without risk | Duplicate |
| The same value is used in many places and may change | Parameter |
| A cleaned table must appear in the model | Leave Enable load on |
| A table is only an intermediate step | Clear Enable load |
Exercise
You have a query SalesStaging that trims and de-duplicates a CSV. You create Customers by choosing Duplicate on it. A week later you add a step to SalesStaging that fixes misspelled region names. The fix does not show up in Customers. Why, and what should you have chosen?
Show answer
Duplicate copies the M code, so Customers has its own independent steps and does not see later changes to SalesStaging. Choosing Reference would make the first step of Customers point at SalesStaging, so the new region fix would flow through. Also clear Enable load on SalesStaging if you do not need it as a table in the model.
Exercise
Write the Source step of a query that reads orders.csv from a folder stored in a text parameter named SourceFolder, using UTF-8 encoding and a comma delimiter.
Show answer
Source = Csv.Document(File.Contents(SourceFolder & "\orders.csv"), [Delimiter = ",", Encoding = 65001])