Up: SQL Expressions
Next: Window functions >

SQL Expressions: Aggregate functions

sq provides some aggregate functions out of the box: COUNT, SUM, AVG, MIN, MAX. They return a NumberField so you can use it as an argument to row.Int, row.Int64 and row.Float64 (see Struct Mapping). Since NumberFields are Fields, aggregate functions can be used anywhere where a Field is expected.
// Aggregate functions
func Count() NumberField
func Sum(field interface{}) NumberField
func Avg(field interface{}) NumberField
func Min(field interface{}) NumberField
func Max(field interface{}) NumberField

Notice that instead of taking in a Field, the above aggregate functions take in an interface{}. This is to allow you also pass subqueries into it. The same rendering logic for Fieldf and Predicatef apply here: you can pass anything into it, it is up to you to preserve the SQL semantics of your query.

If you need to use any other aggregate functions (e.g. array_agg or json_agg) you will need to use Fieldf/Predicatef.

Up: SQL Expressions
Next: Window functions >