---
title: "Fixing WQL COUNT(DISTINCT) with WHERE ON RBO Filter"
description: "Resolve \"Invalid WQL query: Cannot construct instance source on grouped results.\" when combining COUNT(DISTINCT field) and WHERE ON Related Business Object…"
url: https://kiweely.com/guides/wql-count-distinct-with-where-on-rbo-filter
---

# Fixing WQL “Cannot construct instance source on grouped results” with COUNT(DISTINCT)

Combining SELECT COUNT(DISTINCT field) with a WHERE ON Related Business Object (RBO) filter in WQL throws “Invalid WQL query: Cannot construct instance source on grouped results.” unless the PBO WHERE clause also includes WHERE <rbo> IS NOT EMPTY.

-   **Checked** against Workday on November 6
-   Applies to **Workday Query Language**
-   3 min read
-   Published November 6
-   By Kiweely

## Why `COUNT(DISTINCT)` + `WHERE ON` Throws `Cannot construct instance source on grouped results`

When querying a Prism Published Data Source, an Extend Model Business Object, or a Workday reporting data source, you often need to count the unique number of parent values (`SELECT COUNT(DISTINCT field)`) while filtering on a Related Business Object (`RBO`) using `WHERE ON`:

sql

```
SELECT COUNT(DISTINCT cycleName)
FROM appNameWorkerDetails
WHERE ON checkStatus
  statusType = 'Complete'
  AND completionDate >= '2026-06-01'
  AND completionDate <= '2026-07-01'
WHERE department IN (356850fb684a10dec08d71cf278f916d)
```

When you execute this query, Workday returns HTTP `400 Bad Request` with the validation error:

json

```
{
  "error": "Invalid WQL query: Cannot construct instance source on grouped results."
}
```

At first glance, this error makes it look as though WQL does not support combining `COUNT(DISTINCT ...)` with `WHERE ON` RBO filters. In reality, WQL supports `COUNT(DISTINCT field)` alongside `WHERE ON` on both Extend Business Objects and Prism data sources—provided you satisfy one critical PBO filter requirement.

## Root Cause: How `WHERE ON` Interacts with PBO Instance Filtering During Grouping

In WQL, a `WHERE ON <rbo>` clause filters the instances of the Related Business Object, **not** the rows of the Primary Business Object (PBO).

If a PBO row has three `checkStatus` RBO instances and none of them match `statusType = 'Complete'`, the `WHERE ON checkStatus` filter reduces that row’s `checkStatus` collection to empty—but the PBO row itself still remains in the result set unless the PBO `WHERE` clause explicitly excludes rows where `checkStatus` is empty!

When you execute a non-aggregated query (`SELECT cycleName, checkStatus{statusType}`), WQL can evaluate the `WHERE ON` subfilter per row after retrieving the PBO instances. However, when you ask WQL to compute an aggregate over grouped results (`SELECT COUNT(DISTINCT cycleName)`), the query engine must filter the PBO instance source *before* constructing the grouped aggregation buckets. If `WHERE ON checkStatus` is present without `WHERE checkStatus IS NOT EMPTY` in the main `WHERE` clause, the engine attempts to apply the RBO subfilter after grouping the PBO instances, which fails with:

text

```
Invalid WQL query: Cannot construct instance source on grouped results.
```

## The Fix: Pair `WHERE ON <rbo>` with `WHERE <rbo> IS NOT EMPTY`

To allow WQL to construct the filtered PBO instance source before evaluating `COUNT(DISTINCT ...)`, add `<rbo> IS NOT EMPTY` to the main `WHERE` clause for every Related Business Object filtered in a `WHERE ON` clause:

sql

```
SELECT COUNT(DISTINCT cycleName) AS distinctCycleCount
FROM appNameWorkerDetails
WHERE ON checkStatus
  statusType = 'Complete'
  AND completionDate >= '2026-06-01'
  AND completionDate <= '2026-07-01'
WHERE
  checkStatus IS NOT EMPTY
  AND department IN (356850fb684a10dec08d71cf278f916d)
```

With `checkStatus IS NOT EMPTY` in the `WHERE` clause, Workday pushes the RBO existence check (`WHERE ON` + `IS NOT EMPTY`) into the PBO instance filter before grouping and counting distinct `cycleName` values.

### Clause Ordering and Field Type Rules for `COUNT(DISTINCT)` and `WHERE ON`

When writing combined `COUNT(DISTINCT)` and `WHERE ON` queries, verify four additional WQL rules:

1.  **`WHERE ON` must always precede `WHERE`:** Placing `WHERE` before `WHERE ON` is a syntax error in WQL. If you filter multiple RBOs, stack each `WHERE ON <rbo>` clause above the single `WHERE` clause:
    
    sql
    
    ```
    SELECT COUNT(DISTINCT cycleName)
    FROM appNameWorkerDetails
    WHERE ON checkStatus statusType = 'Complete'
    WHERE ON location country IN (bc33aa3152ec42d4995f4791a106ed09)
    WHERE checkStatus IS NOT EMPTY AND location IS NOT EMPTY
    ```
    
2.  **`COUNT(DISTINCT field)` only accepts `Text` and `Single Instance` fields:** As documented in *WQL Reference: SELECT*, you cannot pass a `Multi-Instance`, `Numeric`, `Currency`, or `Boolean` field into `COUNT(DISTINCT field)`.
3.  **Do not include RBO `{}` fields in `SELECT` when using `COUNT(DISTINCT)`:** Because `COUNT(DISTINCT ...)` is an aggregation function, adding `checkStatus{statusType}` to the `SELECT` clause triggers `"You can't use aggregation functions when the SELECT clause specifies a Related Business Object (RBO) field."` Keep `checkStatus` in `WHERE ON` and `WHERE` only.
4.  **Use single quotes for date literals and never pass empty `IN ()` lists:** Format dates as `'YYYY-MM-DD'` and ensure any dynamic `WHERE prismField IN (...)` filter contains at least one valid value.

## Using `Convert Report to WQL` to Verify Complex RBO Filters

If a Prism or Extend data source still rejects a complex `WHERE ON` condition, build a quick custom Advanced Report on the same data source:

1.  Add the PBO field (`cycleName`) on the **Columns** tab.
2.  Add the RBO subfilter (`checkStatus` -> `statusType = 'Complete'`) on the **Subfilter** tab.
3.  Add `checkStatus` **is not empty** on the **Filter** tab.
4.  Run the **Convert Report to WQL** task on that report. Workday will output the exact canonical `WHERE ON` and `WHERE` aliases required by that data source, after which you can wrap the selected field in `COUNT(DISTINCT ...)`.

## How to Verify in the Tenant

1.  Open **View WQL Query Result** in your tenant and first run the query *without* `COUNT(DISTINCT ...)`—selecting `cycleName` and `checkStatus{statusType}` with both `WHERE ON checkStatus ...` and `WHERE checkStatus IS NOT EMPTY`—to verify the exact rows returned.
2.  Replace the `SELECT` list with `SELECT COUNT(DISTINCT cycleName)` while keeping both `WHERE ON checkStatus ...` and `WHERE checkStatus IS NOT EMPTY`.
3.  Confirm that the query executes without `Cannot construct instance source on grouped results` and that the returned integer matches the distinct count of `cycleName` values from Step 1.

## Sources checked

-   [WQL Reference: SELECT](https://developer.workday.com/documentation/GUID-85db8d16-4698-4dea-bef2-23223739c8e6-enHYPHENus)
-   [WQL Reference: WHERE ON](https://developer.workday.com/documentation/GUID-b3109af0-2d98-4e5f-8806-5d4cd7ccace9-enHYPHENus)
-   [WQL Reference: WHERE](https://developer.workday.com/documentation/GUID-a9f9f945-baf1-4a7d-9118-db9a8ce49265-enHYPHENus)
-   [Concept: Related Business Objects in WQL](https://developer.workday.com/documentation/GUID-5295e235-6d69-4b80-ad51-510afbdfb853-enHYPHENus)

## Related guides

[All guides](https://kiweely.com/guides)

-   [### Fixing WQL Error 804 on GROUP BY and Related Business Object Aggregation Limits Grouping a large transactional data source like allActiveAndTerminatedWorkers to populate dropdowns can fail with Error 804 in implementation tenants, while selecting RBO subfields with { } alongside COUNT() or GROUP BY fails validation. Learn the exact WQL grouping rules and solutions.](https://kiweely.com/guides/wql-group-by-error-804-rbo-aggregation-limits)
-   [### Filtering Empty Related Business Objects in WQL and Guarding Omitted RBO Keys in PMD Checking whether a context-linked Related Business Object (RBO) is empty in a WQL WHERE clause can throw “Field: ... can only be used as a related business object field (RBO)”, and empty RBOs are omitted entirely from WQL JSON responses. Learn how to filter empty RBOs and guard PMD scripts.](https://kiweely.com/guides/wql-check-rbo-empty-missing-json-keys-pmd)
-   [### What is Workday Query Language (WQL), and how do you write and run a query? Workday Query Language (WQL) is Workday’s SQL-like language for reading data from data sources and fields instead of reports. You need the Workday Query Language domain in the System functional area; an external caller also needs an API client with System scope.](https://kiweely.com/guides/workday-wql)
-   [### Why does my Workday WQL query fail? The exact error messages and how to fix each one Workday has no WQL message worded ‘instance set invalid for prompt’. A rejected prompt value returns ‘Invalid Parameter Values for parameter’ or ‘does not meet the restrictions defined for this field’. This page quotes each common error as Workday returned it, with the fix.](https://kiweely.com/guides/wql-error-messages)

### More guides on WQL

[All 31 guides](https://kiweely.com/guides#wql)

-   [Why WHERE fieldA = fieldB Throws “Invalid Where Clause” in WQL](https://kiweely.com/guides/wql-compare-two-fields-where-clause-invalid)
-   [Fixing WQL “Specify a valid report field” and HTTP 500 Errors When an ISU Queries Calculated Fields](https://kiweely.com/guides/wql-calculated-field-isu-specify-valid-report-field-500)
-   [Why WQL AVG() Rounds to Whole Numbers and How to Handle Conditional Logic Without CASE](https://kiweely.com/guides/wql-avg-integer-rounding-conditional-logic-without-case)
-   [WQL 500-Instance Related Business Object Limit and Large IN (...) Filter Limits](https://kiweely.com/guides/wql-500-rbo-instances-per-row-large-in-filter-limits)
-   [Fixing WQL HTTP 400 “Parms are required for the fields or data source in the query”](https://kiweely.com/guides/wql-400-parms-are-required-for-fields-or-data-source)
-   [Custom Agent Actions that call Workday SOAP, REST and WQL](https://kiweely.com/guides/workday-custom-agent-actions-soap-rest-wql)
-   [Running WQL in Orchestrate as an integration system user: the security it needs](https://kiweely.com/guides/workday-orchestrate-wql-as-isu)
-   [WQL Cheat Sheet: Workday Query Language Syntax, Data Sources and Working Examples](https://kiweely.com/guides/workday-wql-cheat-sheet)

### From the blog on WQL

[All posts](https://kiweely.com/blog)

-   [What happens after ChatGPT writes your WQL query](https://kiweely.com/blog/after-chatgpt-writes-your-wql)
-   [Answering Executive Span-of-Control and Headcount Questions Live from Workday](https://kiweely.com/blog/executive-org-span-of-control-attrition-questions-live-workday)
-   [Build vs. Buy a Workday MCP Server: OAuth 2.1, SOAP, WQL, and Twice-Yearly Releases](https://kiweely.com/blog/build-vs-buy-workday-mcp-server-engineering-cost)

## Let Workday check the work.

Kiweely writes WQL and builds orchestrations in your own tenant, and Workday, not Kiweely, says whether they passed.

[Start for free](https://kiweely.com/download) [See how it works](https://kiweely.com/vine/how-it-works)

## Get the next guide in your inbox.

One email a month with new guides and one Extend tip. Nothing else.
