Skip to content

COUNT

The Count aggregate function allows you to calculate the number of objects in a table, optionally satisfying some criteria or grouped by values in a column. To use the function, include Count(columnNameInDatabase) into the list of properties requested from the server. For example, the following query retrieves the count of all movies in the database:

GET https://api.backendless.com/<appid>/<REST API key>/data/Movie?props=Count(objectId) 

The query returns the following result, notice the count property in the returned object. The value of the property is the total count of all objects in the table:

[  
    {  
        "count": 8,  
        "___class": "Movie",  
    }  
]

Using Alias

To change the name of the returned property from count to a custom name, use the following syntax:

Count( columnNameInDatabase ) as customPropertyName

For example, the following query returns the total count value in the totalObjects property:

Important

The  value must be URL-encoded. The spaces are replaced with %20:

GET https://api.backendless.com/<appid>/<REST API key>/data/Movie?props=Count(objectId)%20as%20totalObjects

The response for the query now contains the totalObjects property:

[  
    {  
        "totalObjects": 8,  
        "___class": "Movie",  
    }  
]

Grouping Results

Results in the response can be grouped by values from another column. To request grouping of the results, add the groupBy parameter to the request with the value containing the name of the column. For example, the following request returns the number of movies in the database grouped by the year the movies were released:

GET https://api.backendless.com/<appid>/<REST API key>/data/Movie?props=Count(objectId),yearReleased&groupBy=yearReleased

The response for this request contains the number of the movies grouped by the release year:

[  
    {  
        "count": 1,  
        "yearReleased": 1997,  
        "___class": "Movie",  
    },  
    {  
        "count": 1,  
        "yearReleased": 2009,  
        "___class": "Movie",  
    },  
    {  
        "count": 1,  
        "yearReleased": 2011,  
        "___class": "Movie",  
    },  
    {  
        "count": 1,  
        "yearReleased": 2012,  
        "___class": "Movie",  
    },  
    {  
        "count": 4,  
        "yearReleased": 2015,  
        "___class": "Movie",  
    }  
]

Sorting

The results can be sorted using the sortBy parameter. For example, results for the following request will be sorted by the values in the yearReleased column in the descending order:

GET https://api.backendless.com/<appid>/<REST API key>/data/Movie?props=Count(objectId),yearReleased&groupBy=yearReleased&sortBy=yearReleased%20DESC

To sort results by the aggregated value, assign a custom name to the column and sort by that name:

GET https://api.backendless.com/<appid>/<REST API key>/data/Movie?props=Count(objectId)%20as%20movieCount,yearReleased&groupBy=yearReleased&sortBy=movieCount