Aggregates

The query builder also provides a variety of aggregate methods such as count, max, min, and sum. These methods take the headache out of setting up these common aggregate functions.

When executing any of the aggregate functions, any where restrictions on your query will still be applied.

Instead of returning a query, these methods return a simple value.

exists

Returns true if the query returns any rows. Returns false otherwise.

QueryBuilder
query.from( "users" ).where( "username", "like", "jon%" ).exists();
SQL (MySQL)
SELECT COUNT(*) AS aggregate FROM `users` WHERE `username` LIKE 'jon%'

count

Returns an integer number of rows returned by the query.

QueryBuilder
query.from( "users" ).count();
SELECT COUNT(*) AS aggregate FROM `users`

max

Returns the maximum value for the given column.

QueryBuilder
query.from( "users" ).max( "age" );
SQL (MySQL)
SELECT MAX(age) AS aggregate FROM `users`

min

Returns the minimum value for the given column.

QueryBuilder
query.from( "users" ).min( "age" );
SQL (MySQL)
SELECT MIN(age) AS aggregate FROM `users`

sum

Returns the sum of all returned rows for the given column.

QueryBuilder
query.from( "employees" ).sum( "salary" );
SQL (MySQL)
SELECT SUM(salary) AS aggregate FROM `employees`

sumRaw

Returns the sum of all returned rows for the expression.

QueryBuilder
query.from( "accounts" ).sumRaw( "netAdditions + netTransfers" )
SQL (MySQL)
SELECT SUM(netAdditions + netTransfers) AS aggregate FROM `accounts`

columnList

Retrieves the columns for the configured table.

QueryBuilder
query.from( "users" ).columnList();
Result
[ "id", "firstName", "lastName", "username", "email", "password" ]

Last updated