Sub topic 5
Counting rows with COUNTROWS
This chapter assumes you can work in Power BI Desktop's Report view and Fields pane. It also assumes you have a Sales table loaded with a numeric SalesAmount column, and that you can create a measure in the formula bar. You should know that a measure is evaluated at query time inside a filter context, as covered in earlier chapters. Here you will write COUNTROWS measures, learn what they count, and learn how they go wrong.
What COUNTROWS does
COUNTROWS takes a table and returns the number of rows in it, as a whole number. It has one argument, a table or a table expression.
Order Lines = COUNTROWS(Sales)The argument is the whole Sales table, but the measure does not always count every row. A measure is evaluated in the current filter context. That context comes from slicers, visual axes, report filters, and relationships. So COUNTROWS(Sales) counts the rows of Sales that survive those filters.
Put the measure in a card with no filters and it returns the total number of rows. Put it in a table visual with Product Category on the rows, and each category shows the count of Sales rows for that category. Select a year in a slicer, and every number shrinks to that year's rows.
What a row represents
COUNTROWS counts rows, so the answer is only as meaningful as your idea of a row. In this tutorial's Sales table, each row is one order line: one product on one order. The measure is named Order Lines for that reason. If you named it Orders, a reader would assume each order is counted once. An order with three products would then be counted three times, and the number would be wrong.
Before you write a count, check the grain of the table, which is what one row stands for. Ask what a single row represents and name the measure after it.
Following the filter context
The next diagram shows how a measure like Order Lines receives a different table each time the visual asks for a value.
The measure formula is written once. Power BI runs it again for every cell, each time with a different filter context.
Worked example
Suppose the Sales table holds these six rows.
| OrderID | Product | Category | SalesAmount |
|---|---|---|---|
| 1001 | Road Bike | Bikes | 1500 |
| 1001 | Helmet | Accessories | 80 |
| 1002 | Mountain Bike | Bikes | 2200 |
| 1003 | Gloves | Accessories | 40 |
| 1003 | Helmet | Accessories | 80 |
| 1004 | Jersey | Clothing | 90 |
With the Order Lines measure, a card with no filters shows 6. A table visual by Category gives these results.
| Category | Order Lines |
|---|---|
| Accessories | 3 |
| Bikes | 2 |
| Clothing | 1 |
The category counts add up to the grand total of 6. Orders 1001 and 1003 each have two lines, so counting order lines gives a different answer from counting distinct orders. Counting distinct orders needs a different function (DISTINCTCOUNT), which this chapter does not cover.
Counting rows of a filtered table
Because the argument is a table expression, you can pass a filtered table. FILTER takes a table and a condition, and returns only the rows where the condition is true.
Large Order Lines = COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000))FILTER first builds a table of the Sales rows whose SalesAmount is above 1000. COUNTROWS then counts that table. With the sample data above, the result is 2: the Road Bike line (1500) and the Mountain Bike line (2200).
Filters combine. If a slicer limits the report to Category = Accessories, Large Order Lines returns blank, because no Accessories line exceeds 1000. The filter context from the slicer applies first, and the condition inside FILTER narrows the rows further.
Here is how the pieces relate.
| Part | Role |
|---|---|
| `Sales` (first argument of FILTER) | The table to scan. It is already narrowed by the filter context. |
| `Sales[SalesAmount] > 1000` | A condition evaluated once for each row. |
| `FILTER(...)` | Returns the rows where the condition is true. |
| `COUNTROWS(...)` | Counts the rows that FILTER returned. |
Why this form can be slow
FILTER evaluates its condition row by row. On a table with a few thousand rows this does not matter. On tens of millions of rows it can be noticeably slower than other patterns, such as CALCULATE with a simple column condition. Those patterns come later. For learning, and for modest data volumes, COUNTROWS(FILTER(...)) is clear and correct, so use it first and optimize only if a report is slow.
Blank results, not zero
When no rows remain in the filter context, COUNTROWS returns BLANK, not 0. A table visual with a blank measure value normally hides that row, and a card shows an empty value.
This behavior is useful in visuals, because categories with no data do not clutter the table. It can surprise you in two cases:
- A card showing
Large Order Linesfor a slicer selection with no matches appears empty instead of 0. - Arithmetic with a blank result treats the blank as zero in addition, but a divide by a blank denominator fails, which is why
DIVIDEexists.
If you want an explicit zero, add zero to the result. Adding 0 converts BLANK to 0.
Large Order Lines (0 if none) = COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000)) + 0Be careful with this. A measure that always returns a number makes every combination of filters show a row, including combinations that have no data. A table visual can then fill with rows of zeros. Prefer blanks unless the report needs zeros.
Common errors
Counting a column instead of a table
COUNT(Sales[SalesAmount]) counts non-blank values in one column. COUNTROWS(Sales) counts rows. If the column has no blanks the two give the same number, but they mean different things. If SalesAmount has blank cells, COUNT skips them and COUNTROWS does not. Use COUNTROWS when you mean "how many rows", because it states the intent and does not depend on which column you picked.
Passing a column to COUNTROWS
COUNTROWS requires a table. Writing COUNTROWS(Sales[SalesAmount]) returns an error, because a column reference is not a table. Pass Sales or a table expression.
Using a calculated column to count
Some beginners add a calculated column holding 1 on each row and then sum it. That stores a value in every row, uses model memory, and gains nothing. COUNTROWS does the same job as a measure, computed on demand.
Misreading the number
A count of 6 with no filters is not a count of customers or orders unless one row equals one of those. Check the grain, as described above, and name the measure for what a row is.
Relationships and the table you count
In a model with a Sales fact table related to a Product dimension, COUNTROWS(Sales) counts Sales rows. COUNTROWS(Product) counts Product rows, and answers a different question: how many products are in the current filter context. Filters on the Product table flow down to Sales through the relationship, but a count of the Product table is not the same as a count of products sold. Choose the table that matches the question.
Products in Context = COUNTROWS(Product)Using COUNTROWS in a ratio
COUNTROWS measures are often a denominator. In the topic's running example, Average Sales per Order Line divides total sales by the number of order lines.
Total Sales = SUM(Sales[SalesAmount])Average Sales per Order Line = DIVIDE([Total Sales], [Order Lines])A later chapter covers DIVIDE in detail. The point here is that Order Lines can return BLANK when the filters leave no rows, and the ratio must handle that without an error. Because the count is its own measure, you can reuse it in many other measures.
Steps to build and check the measure
- In the Fields pane, select the Sales table.
- On the Home or Table tools tab, choose New measure.
- Enter
Order Lines = COUNTROWS(Sales)in the formula bar and press Enter. - Add a card visual and drag
Order Linesinto it. Confirm the number equals the row count you see in Table view or in Power Query. - Add a slicer on Category or Year and select a value. Confirm that the card changes.
- Format the measure as a whole number with a thousands separator in the Measure tools tab.
Step 4 is a useful habit. Compare the first result of any new measure against a number you can verify independently.
Summary of behavior
| Expression | Counts | Result when no rows match |
|---|---|---|
| `COUNTROWS(Sales)` | Rows of Sales in the current filter context | BLANK |
| `COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000))` | Sales rows in context whose SalesAmount is above 1000 | BLANK |
| `COUNT(Sales[SalesAmount])` | Non-blank values in one column | BLANK |
| `COUNTROWS(Sales[SalesAmount])` | Nothing, this is an error | Error |
Exercise
Using the six-row sample table in this chapter, what does Large Order Lines return in a card when a slicer is set to Category = Accessories, and why does the card look empty rather than showing 0? How would you make it show 0?
Show answer
No Accessories row has a SalesAmount above 1000, so FILTER returns an empty table, and COUNTROWS of an empty table returns BLANK, which a card displays as empty. To show 0, add zero to the result: COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000)) + 0.
Exercise
A colleague writes Orders = COUNTROWS(Sales) and reports that order 1001 in the sample table was counted twice. What is wrong, and what is a better name for the measure?
Show answer
Each row in Sales is one order line, not one order, so an order with two products contributes two rows. The measure counts order lines, and a better name is Order Lines. Counting distinct orders would need a different function, such as DISTINCTCOUNT on the order ID column.
Exercise
Write a measure named Accessory Lines that counts the Sales rows in the Accessories category, regardless of amount, using COUNTROWS and FILTER. What does it return for the sample data with no slicers?
Show answer
Accessory Lines = COUNTROWS(FILTER(Sales, Sales[Category] = "Accessories")). For the sample data it returns 3: the Helmet on order 1001, and the Gloves and Helmet on order 1003.