Skip to content

QueryBuilder

PostgreSQL query builder for Fluxbase SDK Inspired by Supabase’s PostgREST client

Type Parameter Default type
T unknown
  • PromiseLike<PostgrestResponse<T>>

avg(column): this

Calculate the average of a numeric column

Parameter Type Description
column string Column to average

this

Query builder for chaining

// Average price
const { data } = await client.from('products').avg('price').execute()
// Returns: { avg_price: 129.99 }
// Average by category
const { data } = await client.from('products')
.avg('price')
.groupBy('category')
.execute()

count(column?): this

Count rows or a specific column

Parameter Type Description
column? string Column to count (default: ‘*’ for row count)

this

Query builder for chaining

// Count all rows
const { data } = await client.from('users').count().execute()
// Returns: { count: 150 }
// Count non-null values in a column
const { data } = await client.from('orders').count('completed_at').execute()
// Count with grouping
const { data } = await client.from('products')
.count('*')
.groupBy('category')
.execute()
// Returns: [{ category: 'electronics', count: 45 }, { category: 'books', count: 23 }]

groupBy(columns): this

Group results by one or more columns (for use with aggregations)

Parameter Type Description
columns string | string[] Column name(s) to group by

this

Query builder for chaining

// Group by single column
const { data } = await client.from('orders')
.count('*')
.groupBy('status')
.execute()
// Group by multiple columns
const { data } = await client.from('sales')
.sum('amount')
.groupBy(['region', 'product_category'])
.execute()

max(column): this

Find the maximum value in a column

Parameter Type Description
column string Column to find maximum value

this

Query builder for chaining

// Find highest price
const { data } = await client.from('products').max('price').execute()
// Returns: { max_price: 1999.99 }
// Find most recent order
const { data } = await client.from('orders').max('created_at').execute()

min(column): this

Find the minimum value in a column

Parameter Type Description
column string Column to find minimum value

this

Query builder for chaining

// Find lowest price
const { data } = await client.from('products').min('price').execute()
// Returns: { min_price: 9.99 }
// Find earliest date
const { data } = await client.from('orders').min('created_at').execute()

sum(column): this

Calculate the sum of a numeric column

Parameter Type Description
column string Column to sum

this

Query builder for chaining

// Sum all prices
const { data } = await client.from('products').sum('price').execute()
// Returns: { sum_price: 15420.50 }
// Sum by category
const { data } = await client.from('orders')
.sum('total')
.groupBy('status')
.execute()
// Returns: [{ status: 'completed', sum_total: 12500 }, { status: 'pending', sum_total: 3200 }]

deleteMany(): Promise<PostgrestResponse<null>>

Delete multiple rows matching the filters (batch delete)

Deletes all rows that match the current query filters. This is a convenience method that explicitly shows intent for batch operations.

Promise<PostgrestResponse<null>>

Promise confirming deletion

// Delete all inactive users
await client.from('users')
.eq('active', false)
.deleteMany()
// Delete old logs
await client.from('logs')
.lt('created_at', '2024-01-01')
.deleteMany()

insertMany(rows): Promise<PostgrestResponse<T>>

Insert multiple rows in a single request (batch insert)

This is a convenience method that explicitly shows intent for batch operations. Internally calls insert() with an array.

Parameter Type Description
rows Partial<T>[] Array of row objects to insert

Promise<PostgrestResponse<T>>

Promise with the inserted rows

// Insert multiple users at once
const { data } = await client.from('users').insertMany([
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' },
{ name: 'Charlie', email: 'charlie@example.com' }
])

updateMany(data): Promise<PostgrestResponse<T>>

Update multiple rows matching the filters (batch update)

Updates all rows that match the current query filters. This is a convenience method that explicitly shows intent for batch operations.

Parameter Type Description
data Partial<T> Data to update matching rows with

Promise<PostgrestResponse<T>>

Promise with the updated rows

// Apply discount to all electronics
const { data } = await client.from('products')
.eq('category', 'electronics')
.updateMany({ discount: 10, updated_at: new Date() })
// Mark all pending orders as processing
const { data } = await client.from('orders')
.eq('status', 'pending')
.updateMany({ status: 'processing' })

and(filters): this

Apply AND logic to filters (Supabase-compatible) Groups multiple conditions that must all be true

Parameter Type
filters string

this

and('status.eq.active,verified.eq.true')
and('age.gte.18,age.lte.65')

between(column, min, max): this

Filter column value within an inclusive range (BETWEEN) Generates: AND (column >= min AND column <= max)

Parameter Type Description
column string Column name to filter
min unknown Minimum value (inclusive)
max unknown Maximum value (inclusive)

this

between('recorded_at', '2024-01-01', '2024-01-10')
between('price', 10, 100)

clone(): QueryBuilder<T>

Create a deep copy of this query builder, preserving all filters, ordering, and state. Useful for paginating: build a base query once, then call .range() on it for each page (.range() returns a clone automatically).

QueryBuilder<T>

const base = client.from('orders').select('*').eq('status', 'active')
const p1 = await base.clone().range(0, 9)
const p2 = await base.clone().range(10, 19)

containedBy(column, value): this

Check if column is contained by value (Supabase-compatible) For arrays and JSONB

Parameter Type
column string
value unknown

this

containedBy('tags', '["news","update"]')

contains(column, value): this

Contains (for arrays and JSONB)

Parameter Type
column string
value unknown

this


crosses(column, geojson): this

Check if geometries cross (PostGIS ST_Crosses)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test crossing

this

crosses('road', { type: 'LineString', coordinates: [[...]] })

delete(): this

Delete rows matching the filters

this


eq(column, value): this

Equal to

Parameter Type
column string
value unknown

this


execute(): Promise<PostgrestResponse<T>>

Execute the query and return results

Promise<PostgrestResponse<T>>


filter(column, operator, value): this

Generic filter method using PostgREST syntax (Supabase-compatible)

Parameter Type
column string
operator FilterOperator
value unknown

this

filter('name', 'in', '("Han","Yoda")')
filter('age', 'gte', '18')
filter('recorded_at', 'between', ['2024-01-01', '2024-01-10'])
filter('recorded_at', 'not.between', ['2024-01-01', '2024-01-10'])

gt(column, value): this

Greater than

Parameter Type
column string
value unknown

this


gte(column, value): this

Greater than or equal to

Parameter Type
column string
value unknown

this


ilike(column, pattern): this

Pattern matching (case-insensitive)

Parameter Type
column string
pattern string

this


in(column, values): this

Check if value is in array

Parameter Type
column string
values unknown[]

this


insert(data): this

Insert a single row or multiple rows

Parameter Type
data Partial<T> | Partial<T>[]

this


intersects(column, geojson): this

Check if geometries intersect (PostGIS ST_Intersects)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test intersection with

this

intersects('location', { type: 'Point', coordinates: [-122.4, 37.8] })

is(column, value): this

Check if value is null or not null

Parameter Type
column string
value boolean | null

this


like(column, pattern): this

Pattern matching (case-sensitive)

Parameter Type
column string
pattern string

this


limit(count): this

Limit number of rows returned

Parameter Type
count number

this


lt(column, value): this

Less than

Parameter Type
column string
value unknown

this


lte(column, value): this

Less than or equal to

Parameter Type
column string
value unknown

this


match(conditions): this

Match multiple columns with exact values (Supabase-compatible) Shorthand for multiple .eq() calls

Parameter Type
conditions Record<string, unknown>

this

match({ id: 1, status: 'active', role: 'admin' })

maybeSingle(): this

Return a single row or null (adds limit(1)) Does not error if no rows found (Supabase-compatible)

this

// Returns null instead of erroring when no row exists
const { data, error } = await client
.from('users')
.select('*')
.eq('id', 999)
.maybeSingle()
// data will be null if no row found

neq(column, value): this

Not equal to

Parameter Type
column string
value unknown

this


not(column, operator, value): this

Negate a filter condition (Supabase-compatible)

Parameter Type
column string
operator FilterOperator
value unknown

this

not('status', 'eq', 'deleted')
not('completed_at', 'is', null)

notBetween(column, min, max): this

Filter column value outside an inclusive range (NOT BETWEEN) Generates: OR (column < min OR column > max) Multiple notBetween calls on the same column AND together

Parameter Type Description
column string Column name to filter
min unknown Minimum value of excluded range
max unknown Maximum value of excluded range

this

notBetween('recorded_at', '2024-01-01', '2024-01-10')
notBetween('price', 0, 10) // Excludes items priced 0-10

offset(count): this

Skip rows

Parameter Type
count number

this


or(filters): this

Apply OR logic to filters (Supabase-compatible)

Parameter Type
filters string

this

or('status.eq.active,status.eq.pending')
or('id.eq.2,name.eq.Han')

order(column, options?): this

Order results

Parameter Type
column string
options? { ascending?: boolean; nullsFirst?: boolean; }
options.ascending? boolean
options.nullsFirst? boolean

this


orderByVector(column, vector, metric?, options?): this

Order results by vector similarity (pgvector) Results are ordered by distance (ascending = closest first)

Parameter Type Description
column string The vector column to order by
vector number[] The query vector to compare against
metric? VectorMetric Distance metric: ‘l2’ (euclidean), ‘cosine’, or ‘inner_product’
options? { ascending?: boolean; } Optional: { ascending?: boolean } - defaults to true (closest first)
options.ascending? boolean -

this

// Order by cosine similarity (closest matches first)
const { data } = await client
.from('documents')
.select('id, title, content')
.orderByVector('embedding', queryVector, 'cosine')
.limit(10)

overlaps(column, value): this

Check if arrays have common elements (Supabase-compatible)

Parameter Type
column string
value unknown

this

overlaps('tags', '["news","sports"]')

range(from, to): QueryBuilder<T>

Range selection (pagination)

Returns a clone of the builder with the new range applied, so the original builder can be reused for subsequent pages:

Parameter Type
from number
to number

QueryBuilder<T>

const base = client.from('orders').select('*').order('id')
const page1 = await base.range(0, 9) // rows 0-9
const page2 = await base.range(10, 19) // rows 10-19 (works!)

select(columns?, options?): this

Select columns to return

Parameter Type
columns? string
options? SelectOptions

this

select('*')
select('id, name, email')
select('id, name, posts(title, content)')
select('*', { count: 'exact' }) // Get exact count
select('*', { count: 'exact', head: true }) // Get count only (no data)

single(): this

Return a single row (adds limit(1)) Errors if no rows found

this


stContains(column, geojson): this

Check if geometry A contains geometry B (PostGIS ST_Contains)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test containment

this

contains('region', { type: 'Point', coordinates: [-122.4, 37.8] })

stOverlaps(column, geojson): this

Check if geometries spatially overlap (PostGIS ST_Overlaps)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test overlap

this

stOverlaps('area', { type: 'Polygon', coordinates: [[...]] })

textSearch(column, query): this

Full-text search

Parameter Type
column string
query string

this


then<TResult1, TResult2>(onfulfilled?, onrejected?): PromiseLike<TResult1 | TResult2>

Make QueryBuilder awaitable (implements PromiseLike) This allows using await client.from('table').select() without calling .execute()

Type Parameter Default type
TResult1 PostgrestResponse<T>
TResult2 never
Parameter Type
onfulfilled? ((value) => TResult1 | PromiseLike<TResult1>) | null
onrejected? ((reason) => TResult2 | PromiseLike<TResult2>) | null

PromiseLike<TResult1 | TResult2>

// Without .execute() (new way)
const { data } = await client.from('users').select('*')
// With .execute() (old way, still supported)
const { data } = await client.from('users').select('*').execute()

PromiseLike.then


throwOnError(): Promise<T>

Execute the query and throw an error if one occurs (Supabase-compatible) Returns the data directly instead of { data, error } wrapper

Promise<T>

If the query fails or returns an error

// Throws error instead of returning { data, error }
try {
const user = await client
.from('users')
.select('*')
.eq('id', 1)
.single()
.throwOnError()
} catch (error) {
console.error('Query failed:', error)
}

touches(column, geojson): this

Check if geometries touch (PostGIS ST_Touches)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test touching

this

touches('boundary', { type: 'LineString', coordinates: [[...]] })

truncate(length): this

Truncate text columns to specified length Useful for browsing tables with large text fields

Parameter Type
length number

this

truncate(500) // Truncate text columns to 500 characters

update(data): this

Update rows matching the filters

Parameter Type
data Partial<T>

this


upsert(data, options?): Promise<PostgrestResponse<T>>

Upsert (insert or update) rows (Supabase-compatible)

Parameter Type Description
data Partial<T> | Partial<T>[] Row(s) to upsert
options? UpsertOptions Upsert options (onConflict, ignoreDuplicates, defaultToNull)

Promise<PostgrestResponse<T>>


vectorSearch(column, vector, metric?): this

Filter by vector similarity (pgvector) This is a convenience method that adds a vector filter using the specified distance metric. Typically used with orderByVector() for similarity search.

Parameter Type Description
column string The vector column to search
vector number[] The query vector
metric? VectorMetric Distance metric: ‘l2’ (euclidean), ‘cosine’, or ‘inner_product’

this

// Find the 10 most similar documents
const { data } = await client
.from('documents')
.select('id, title, content')
.vectorSearch('embedding', queryVector, 'cosine')
.limit(10)
// Combine with other filters
const { data } = await client
.from('documents')
.select('id, title, content')
.eq('status', 'published')
.vectorSearch('embedding', queryVector)
.limit(10)

within(column, geojson): this

Check if geometry A is within geometry B (PostGIS ST_Within)

Parameter Type Description
column string Column containing geometry/geography data
geojson unknown GeoJSON object to test containment within

this

within('point', { type: 'Polygon', coordinates: [[...]] })