Blog
SQL - Caution - the Distinct function may not return the records that you expect!
One thing that can catch out app builders is that the Distinct function is not delegable. This post illustrates this problem through an example that shows how the distinct function may not return all records that we expect.
Recreating the problem
To recreate the problem, let's create an app and set the row count limit to 10. Whenever we test an app, a great tip is to set the row count limit to a low value. This makes it more obvious if an app doesn't return the expected records.
We'll attempt to show the distinct country values form a table called Property. From SQL Server, we see that there are 207 distinct values.
The Distinct function is not delegable
From Power Apps, we call the Distinct function to return the distinct countries.Distinct('[dbo].[Property]', Country).Result
When we profile the call to SQL Server, we see that Power Apps attempts to resolve the distinct function by selecting the top 10 records only from the property table. From this, we can conclude that the distinct function is not delegable
How to correctly return distinct values from a table
The correct way to return distinct values in a delegable way is to build a view, which is covered in my post here.http://powerappsguide.com/blog/post/sql-showing-distinct-values-the-correct-way
We define a view in SQL Server that returns the distinct countries and connect to this view from our app.
CREATE VIEW [dbo].[vw_DistinctCountries]The view will be completely delegable, and will return the expected results.
AS
SELECT DISTINCT Country
FROM
[dbo].[Property]
Conclusion
- Categories:
- sql
- SQL - How to return data from Stored Procedures to Power Apps
- SQL - How to call SQL Server Stored procedures more easily with the help of Dataverse plugins
- Dataverse - How to connect to SQL Server in Model Driven/Portal apps through virtual tables
- Forms - How to add and edit records against SQL Server tables GUID primary keys
- SQL - What to do when edit/add/delete options missing from an app, or edit controls unavailable in forms
- SQL - How to configure case sensitive or case insensitve searches against SQL Server data sources
- SQL - How to lookup/display related details with SQL Server Views
- Data - How to apply customize sort sequences with SQL and Power Apps
- SQL - How to show distinct values in the most efficient way
- Dataverse - How to access data more easily through TDS
- SQL - What you need to know about bulk updating records