Grails Cookbook - A collection of tutorials and examples

Grails Criteria Count Example

This post will show how to get the total number of result with GORM criteria by using the count aggregate function inside criteria projections.

If you are new to the Criteria API, you may read these previous post on createCriteria method and Criteria API.

Examples

We can use the aggregate function count with projections to get the number of resulting records. Here is a simple example of using Grails Criteria Count:

def criteria = Person.createCriteria()
def result = criteria.list {
    projections {
        count()
    }
}
println "The number of people is ${result[0]}"

Here is a slightly modified version that includes a where clause (firstName = 'John').

def criteria = Person.createCriteria()
def result = criteria.list {
    projections {
        count()
    }
    eq ('firstName', 'John')
}
println "The number of people with first name 'John' is ${result[0]}"