Skip to content

Retrieving Unique Objects

Unique objects can be retrieved from a column of the requested table by setting the true value in the setDistinct method, The distinct parameter is a boolean value which defaults to false.

Consider the following table schema for a data table called Employees:

retrieving_unique_objects_1

This table contains the column firstName, and by passing the true value to the setDistinct method, only unique values will be returned in the response:

const query = Backendless.DataQueryBuilder.create()  
query.addProperty('firstName')  
query.setDistinct(true)  

const result = await Backendless.Data.of('Employees').find(query)

The query returns the following result which contains only unique names:

[  
    {  
        "___class": "Employees",  
        "firstName": "Anna"  
    },  
    {  
        "___class": "Employees",  
        "firstName": "Simon"  
    },  
    {  
        "___class": "Employees",  
        "firstName": "Andrew"  
    }  
]

Aggregate Functions

The distinct parameter can be also used with such aggregate functions as:

Average

Suppose you need to calculate an average value for a set of objects, but you want to skip identical records. The following example will retrieve only unique values from the age column and calculate the average age of all employees.

const query = Backendless.DataQueryBuilder.create()  
query.addProperty('Avg(distinct age')  
query.setDistinct(true)  

const result = await Backendless.Data.of('Employees').find(query)

Count

The example below will count only unique values in the firstName column and return an integer value in the response:

const query = Backendless.DataQueryBuilder.create()  
query.addProperty('Count(distinct firstName')  
query.setDistinct(true)  

const result = await Backendless.Data.of('Employees').find(query)

Sum

The example below will calculate the sum of unique values in the bonusPayment column and return an integer value in the response:

const query = Backendless.DataQueryBuilder.create()  
query.addProperty('Sum(distinct bonusPayment')  
query.setDistinct(true)  

const result = await Backendless.Data.of('Employees').find(query)