Aggregation Queries
groupBy
Groups results.distinct
Returns results with duplicates removed. Uses the SQLDISTINCT clause.
having
Filters grouped results.Data Modification
insert
Inserts new records.update
Updates records.delete
Deletes records.increment / decrement
Increments/decrements numeric columns.Row Locking
Acquire locks on SELECTed rows within a transaction to prevent concurrent modifications by other transactions.forUpdate
Acquires an exclusive lock on selected rows, preventing other transactions from modifying or locking those rows.forShare
Acquires a shared lock on selected rows, preventing other transactions from modifying those rows while still allowing reads.Under PostgreSQL MVCC, row-level locks (
FOR UPDATE / FOR SHARE) do not block plain SELECT reads. Only other lock requests and write operations on the same rows are blocked.Fetching Results
first
Fetches only the first record.pluck
Fetches only specific column values as an array.Vector Similarity Search
vectorSimilarity
Vector similarity search using pgvector.method: Similarity measurement methodcosine: Cosine similarity (0~1, higher is more similar)l2: Euclidean distance (lower is more similar)inner_product: Inner product (higher is more similar)
threshold: Similarity filtering thresholddistinctOn: Returns only the most similar result per unique column value
distinctOn Option
ThedistinctOn option allows you to retrieve only the most similar result for each unique value in a specified column. It leverages PostgreSQL’s DISTINCT ON clause.
distinctOn with threshold:
When using the
distinctOn option, the query is internally wrapped in a subquery and sorted by
similarity in descending order in the outer query.Upsert (INSERT or UPDATE)
onConflict
Specifies action on conflict.returning
Returns inserted/updated records.Utility Methods
clone
Clones a query.debug
Prints generated SQL to console.toQuery
Returns SQL query string.raw
Executes raw SQL.Real-World Examples
- Statistics Query
- Batch Update
- Upsert Pattern
- Vector Search
- Transaction
- Conditional Query
Performance Optimization
Batch INSERT
increment vs UPDATE
HAVING vs WHERE
Cautions
1. increment/decrement Values
2. onConflict Constraints
3. returning
4. vectorSimilarity Requires pgvector
Next Steps
select
Select fields to retrieve
where
Filter conditions
UpsertBuilder
Handle bulk upserts
Transactions
Use transactions