Skip to main content

StringAgg

Builds a string_agg(field, 'delimiter' [order by ...]) expression, usable anywhere an SQL element is accepted (typically as a Select column).

Constructor

StringAgg(field: string | SqlElement, delimiter?: string): StringAgg
new StringAgg(field: string | SqlElement, delimiter?: string): StringAgg

Dual-callable. A string field is wrapped in a Field instance; delimiter defaults to ','.

import { StringAgg, Select } from '@sqb/builder';

Select('country', StringAgg('name').delimiter(', ').as('names'))
.from('customers')
.groupBy('country');
// select country, string_agg(name,', ') names from customers group by country

Properties

KeyTypeReadonlyDescription
_typeSerializationType.STRINGAGG_STATEMENTYesDiscriminates this node during serialization.
_fieldSqlElementNoThe aggregated field, set from the constructor (always a Field when constructed from a string).
_delimiterstringNoThe separator between values; defaults to ','.
_orderBy(OrderColumn | SqlElement)[] | undefinedNoColumns added by .orderBy().
_aliasstring | undefinedNoSet by .as().

Methods

delimiter()

delimiter(value: string): this

Sets the separator placed between aggregated values.

orderBy()

orderBy(...field: (string | SqlElement)[]): this

Adds an ORDER BY clause inside the aggregate; strings become OrderColumn instances (supporting the same +/-/asc/desc syntax as Select#orderBy()).

StringAgg('name').orderBy('-created_at').as('names_by_recency');
// string_agg(name,',' order by created_at desc) names_by_recency

as()

as(alias: string): this

Sets an alias, rendered as a trailing alias after the closing paren (no AS keyword).

See also