---
title: QueryBuilder
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/querybuilder/
updated: 2026-11-19T20:13:51.296Z
---

# QueryBuilder

> DATA, DB(), NEWDB() and the methods of the QueryBuilder.

The global `DATA`, the `DB()` chain and the adapters registered with `NEWDB()`, together with every method of the QueryBuilder that they return. An introduction with examples is in the guide [QueryBuilder](../../guides/querybuilder/).

## API

### DATA

Type: `property`

The global database object that starts each query immediately.

Returns: `Database`

A shared instance of the database controller. Every operation on it (`find()`, `insert()`…) creates a QueryBuilder and executes it on the next tick, independently of other queries. Use `DB()` when you need several queries in a sequence with one result.

Example: Find rows
```js
DATA.find('users').where('isremoved', false).callback(function(err, response) {
	console.log(response);
});
```

### DB()

Type: `method`

Creates a database object that runs queries in sequence.

Returns: `Database` A new database controller.

Each operation you call on the returned object is queued and executed in order after the current tick. The final response is the result of the last query, or an object filled by `set(name)` of each query. The first error stops the chain and is passed to `callback()`. If you add a query after the chain finished, the chain starts again.

Example: Two queries
```js
var db = DB();
db.read('users').id('u1').set('user');
db.find('orders').where('userid', 'u1').set('orders');
db.callback(function(err, response) {
	// response.user, response.orders
});
```

### NEWDB([name], [fn])

Type: `method`

Registers or removes a database adapter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `'default'` | The connection name. |
| `fn` | `Function` | no |  | `function(filter, callback)` that executes the query. Omit it to remove the adapter. |

The adapter executes the queries of the connection `name`. It is called with `this` as the internal query object, `filter` as the options of the query (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) and a callback `(err, response)`. The `checksum` is a short hash of the structure of the filter, useful as a cache key for prepared queries. The adapter `*` is used for connections without their own adapter. Without `fn` the adapter `name` is removed; `name` is required then. The framework registers the adapter `nosql` for the embedded NoSQL files, and `DATA.init()` registers adapters for PostgreSQL (see [PostgreSQL](../../reference/postgresql/)).

Example: A logging adapter
```js
NEWDB('default', function(filter, callback) {
	console.log(filter.exec, filter.table, filter.filter);
	callback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);
});
```

### db.find(table)

Type: `method`

Finds all rows that match the filter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `find`. The response is the array that the adapter returns. Alias: `db.all()`.

Example: Find
```js
DATA.find('products').where('price', '>', 10).sort('name').callback(console.log);
```

### db.read(table)

Type: `method`

Reads one row.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `read`, `take` 1 and the `first` option. When the adapter returns an array, the response is its first item or `null`. Alias: `db.one()`.

Example: Read by id
```js
DATA.read('users').id('u1').error('@(User not found)').callback(console.log);
```

### db.list(table)

Type: `method`

Reads one page of rows with paging metadata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `list`, `skip` 0 and `take` 100. The adapter returns an object with the rows and the total `count`; the `nosql` adapter returns `{ items, count }`, where `count` is the number of all matching documents. The QueryBuilder adds `page`, `limit` and `pages` to that object.

Example: A page
```js
DATA.list('products').page(2, 20).callback(function(err, response) {
	console.log(response.items, response.count, response.pages);
});
```

### db.check(table)

Type: `method`

Checks whether a row exists.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `check`, `take` 1 and the `first` option. The adapter answers whether a row matches (the `nosql` adapter returns `true` or `false`).

Example: Unique e-mail
```js
DATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);
```

### db.count(table)

Type: `method`

Counts the rows that match the filter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `count`. The adapter decides the form of the response.

Example: Count
```js
DATA.count('orders').where('status', 'paid').callback(console.log);
```

### db.scalar(table, type, [key], [key2])

Type: `method`

Computes an aggregate value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |
| `type` | `String` | yes |  | The aggregate, for example `sum`, `avg`, `min`, `max`, `count`. |
| `key` | `String` | no | `'*'` | The column. |
| `key2` | `String` | no |  | A second column to group by `key`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `scalar` and the option `scalar = { type, key, key2 }`. `key` defaults to `*`. With `key2` the adapter groups the values of `key2` by `key`. The types are interpreted by the adapter; the `nosql` adapter supports `min`, `max`, `sum`, `avg` and `count` (without `key2`; with the default `*` each document counts as `1`), and `group` (`key2` sums the values of `key2` per `key`).

Example: Sum
```js
DATA.scalar('orders', 'sum', 'price').where('status', 'paid').callback(console.log);
```

### db.insert(table, data)

Type: `method`

Inserts a row.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |
| `data` | `Object` | yes |  | The row to insert. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `insert` and `data` as the payload. Alias: `db.ins()`.

Example: Insert
```js
DATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);
```

### db.update(table, data, [upsert])

Type: `method`

Updates the rows that match the filter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |
| `data` | `Object` | yes |  | The columns to change. |
| `upsert` | `Boolean` | no | `false` | Insert the payload when nothing was updated. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `update` and `data` as the payload. With `upsert` set to `true`, an update that returns no result (or an empty `returning` result) is executed again as an `insert` of the same payload with no conditions; `builder.insert(fn)` can change the payload before that. Aliases: `db.modify()`, `db.mod()`, `db.upd()`.

Example: Update
```js
DATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);
```

### db.remove(table)

Type: `method`

Removes the rows that match the filter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `remove`. Alias: `db.rem()`.

Example: Remove
```js
DATA.remove('users').id('u1').callback(console.log);
```

### db.query([connection], query, [params])

Type: `method`

Runs a raw query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `connection` | `String` | no | `'default'` | The connection name. |
| `query` | `String` | yes |  | The raw query. |
| `params` | `Object|Array` | no |  | Parameters for the adapter. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `query` and the options `query` and `params`. With one argument (or when the second argument is an object) the query runs on the connection `default`; otherwise the first argument is the connection name. The adapter decides the syntax of the query and of the parameters.

Example: Raw SQL
```js
DATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').callback(console.log);
```

### db.truncate(table)

Type: `method`

Removes all rows of a table.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |

Returns: `QueryBuilder`

Returns a QueryBuilder with the operation `truncate`. Alias: `db.clear()`. `db.drop(table)` works the same with the operation `drop`, and `db.command(table, name)` with the operation `command` and the option `command = name`, for custom commands of the adapter.

Example: Truncate
```js
DATA.truncate('logs/requests').callback(console.log);
```

### db.exec(filter, callback)

Type: `method`

Runs a query described by a plain object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filter` | `Object` | yes |  | The options, for example `{ exec: 'find', table: 'users', take: 10 }`. |
| `callback` | `Function` | yes |  | `function(err, response)`. |

`filter.exec` selects the operation (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` or `query`) and `filter.table` the table; every other key is copied into the options of the query. For `query` the raw query is in `filter.query`.

Example: Exec
```js
DATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);
```

### db.load([connection], options)

Type: `method`

Creates a query from prepared options.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `connection` | `String` | no | `'default'` | The connection name. |
| `options` | `Object` | yes |  | The prepared options. |

Returns: `QueryBuilder`

Creates a QueryBuilder from an object with `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` and `filter` (an array of filter items). The connection defaults to `default`.

Example: Load
```js
DATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);
```

### db.language(prefix, skip)

Type: `method`

Sets the defaults for localized columns.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `prefix` | `String` | yes |  | The prefix put before the language code. |
| `skip` | `String` | yes |  | A language that means "no language". |

Returns: `Database`

Sets the global prefix and the language to skip that `builder.language()` uses when it gets no own values. The default skipped language is `_`.

Example: Defaults
```js
DATA.language('_', 'en');
```

### db.debug()

Type: `method`

Sets the debug option on every query of a DB() chain.

Returns: `Database`

Each query created after this call gets the option `debug = true`, so an adapter that supports it can log the generated query.

Example: Debug
```js
var db = DB().debug();
db.find('users');
db.callback(console.log);
```

### db.callback(fn)

Type: `method`

Sets the callback of a DB() chain.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|$` | yes |  | `function(err, response)` or the `$` of an action. |

Returns: `Database`

The callback gets the first error or the final response. Pass `$` of an action instead of a function to answer the action. Alias: `db.pipe()`.

Example: Callback
```js
var db = DB();
db.read('users').id('u1').set('user');
db.callback($);
```

### db.promise([$])

Type: `method`

Returns a promise of a DB() chain.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | The `$` of an action. |

Returns: `Promise`

The promise resolves with the final response. On error it is rejected, or, with `$`, the error goes to `$.invalid()`.

Example: Await
```js
var db = DB();
db.read('users').id('u1').set('user');
db.find('orders').where('userid', 'u1').set('orders');
var response = await db.promise($);
```

### db.done($, fn)

Type: `method`

Calls fn on success and $.invalid() on error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action. |
| `fn` | `Function` | no |  | `function(response)`. |

Returns: `Database`

Ends a DB() chain inside an action: an error is passed to `$.invalid()`, a response to `fn(response)`.

Example: Done
```js
var db = DB();
db.read('users').id($.params.id).set('user');
db.done($, function(response) {
	$.callback(response.user);
});
```

### builder.where(name, [comparer], value)

Type: `method`

Adds a comparison.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |
| `value` | `Object` | yes |  | The value. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Without `comparer` the comparison is `=`. `==` becomes `=` and `!=` becomes `<>`. With only `name`, the argument is a raw condition, the same as `query()`.

Example: Where
```js
DATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);
```

### builder.id(value)

Type: `method`

Filters by the column id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes |  | An id or a list of ids. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

`where('id', value)`, or `in('id', value)` when the value is an array.

Example: Id
```js
DATA.read('users').id('u1').callback(console.log);
```

### builder.userid(value)

Type: `method`

Filters by the column userid.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array|Object` | yes |  | An id, a list, a user or `$`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Accepts an id, an array of ids (`in`), a user object (its `id`) or an object with `user` such as `$` of an action (its `user.id`).

Example: Rows of the current user
```js
DATA.find('orders').userid($).callback($);
```

### builder.equal(obj)

Type: `method`

Adds one equality per key.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | Column names and values. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Calls `where(key, value)` for every key of the object.

Example: Equal
```js
DATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);
```

### builder.in(name, value, [key])

Type: `method`

The column is one of the values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `value` | `Array` | yes |  | The values. |
| `key` | `String` | no |  | A property to read from each object of `value`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

A single value is wrapped in an array. With `key`, `value` is an array of objects and the values are taken from their property `key`.

Example: In
```js
DATA.find('users').in('id', orders, 'userid').callback(console.log);
```

### builder.notin(name, value, [key])

Type: `method`

The column is none of the values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `value` | `Array` | yes |  | The values. |
| `key` | `String` | no |  | A property to read from each object of `value`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

The opposite of `in()`, with the same arguments.

Example: Not in
```js
DATA.find('users').notin('role', ['guest']).callback(console.log);
```

### builder.between(name, a, b)

Type: `method`

The column is between two values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `a` | `Object` | yes |  | The lower value. |
| `b` | `Object` | yes |  | The upper value. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Adds a `between` item with `a` and `b`.

Example: Last week
```js
DATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);
```

### builder.search(name, value, [where])

Type: `method`

Searches text in a column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `value` | `String` | yes |  | The text. |
| `where` | `String` | no |  | `beg` or `end`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

The column contains `value`. With `where` set to `beg` the text must be at the beginning, with `end` at the end.

Example: Search
```js
DATA.find('products').search('name', 'phone').callback(console.log);
```

### builder.or(fn)

Type: `method`

Joins a group of conditions with OR.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(builder)`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

The filters added inside `fn` form one group. `fn` is called with the builder as `this` and as the argument. An empty group is ignored.

Example: Or
```js
DATA.find('users').or(function(builder) {
	builder.where('role', 'admin');
	builder.where('role', 'editor');
}).callback(console.log);
```

### builder.contains(name)

Type: `method`

The column has a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Adds a `contains` item: the column is not empty (for arrays: it has items). `empty(name)` is the opposite: the column has no value.

Example: Contains
```js
DATA.find('users').contains('phone').callback(console.log);
```

### builder.array(name, [comparer], value)

Type: `method`

A condition on an array column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `comparer` | `String` | no | `'&&'` | The comparer. |
| `value` | `Array|String` | yes |  | The values. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Adds an `array` item. The default comparer is `&&` (the arrays overlap); the adapter interprets it.

Example: Tags
```js
DATA.find('products').array('tags', ['sale', 'new']).callback(console.log);
```

### builder.year(name, [comparer], value)

Type: `method`

Compares a part of a date.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The date column. |
| `comparer` | `String` | no | `'='` | The comparer. |
| `value` | `Number` | yes |  | The value of the part. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Compares the year of a date column. `month()`, `day()`, `hour()` and `minute()` have the same arguments and compare that part. The default comparer is `=`.

Example: Date parts
```js
DATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);
```

### builder.query(value)

Type: `method`

Adds a raw condition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes |  | The raw condition. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

The text is passed to the adapter as it is, so it must be in the syntax of the engine.

Example: Raw
```js
DATA.find('users').query('age > 18').callback(console.log);
```

### builder.join(name, table, type, a, b)

Type: `method`

Adds a join item for the adapter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the join. |
| `table` | `String` | yes |  | The joined table. |
| `type` | `String` | yes |  | The join type. |
| `a` | `String` | yes |  | The column of the main table. |
| `b` | `String` | yes |  | The column of the joined table. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Adds `{ type: 'join', name, table, join: type, on: [a, b] }` to the filter. Whether joins are supported is up to the adapter.

Example: Join
```js
DATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);
```

### builder.permit(name, type, value, [userid], [required])

Type: `method`

Adds a permission condition for the adapter.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column with permissions. |
| `type` | `String` | yes |  | The letters `R`, `W`, `D`. |
| `value` | `Array` | yes |  | Roles or groups. |
| `userid` | `String` | no |  | The id of the user. |
| `required` | `Boolean` | no | `true` | The permission is required. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Each letter of `type` (`R` read, `W` write, `D` delete) is combined with each item of `value`, so `permit('permissions', 'RW', ['admin'])` gives `['Radmin', 'Wadmin']`. The item also carries `userid` and `required` (default `true`).

Example: Permit
```js
DATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).callback($);
```

### builder.fields(fields)

Type: `method`

Selects the columns.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | yes |  | For example `id,name,email`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

A comma-separated list of columns.

Example: Fields
```js
DATA.find('users').fields('id,name,email').callback(console.log);
```

### builder.gridfields(fields, [allowed])

Type: `method`

Selects the columns from an untrusted list.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | no |  | The requested fields, for example `id,name`. Can be empty or `undefined`. |
| `allowed` | `String` | no |  | The fields that may be selected, for example `id,name,price`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Takes a comma-separated list, usually `$.query.fields`, and selects the fields that are also in `allowed`. Quotes, backticks, `|` and spaces are removed first. Empty names are skipped. When the list is empty or missing, or none of the fields is allowed, the selection does not change (all columns). Without `allowed` every field of the list is selected.

Example: Fields from the query string
```js
DATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);
```

### builder.sort(name, [desc])

Type: `method`

Adds a sort column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The column. |
| `desc` | `Boolean|String` | no | `false` | `true` or `desc` for descending. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

`desc` can be `true` or `'desc'`; anything else sorts ascending. Several calls add more columns.

Example: Sort
```js
DATA.find('products').sort('price', true).sort('name').callback(console.log);
```

### builder.gridsort(sort, [map])

Type: `method`

Adds sort columns from a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String` | yes |  | The sort string. |
| `map` | `Object` | no |  | Field names mapped to columns. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

The string has the form `name_asc,dtcreated_desc`; a name without a suffix is ascending. `map` can rename the fields to columns.

Example: Gridsort
```js
DATA.find('products').gridsort('price_desc,name').callback(console.log);
```

### builder.take(count)

Type: `method`

Sets the maximum number of rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The number of rows. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Alias: `limit()`. `first()` sets `take` to 1 and returns only the first row. `skip(count)` sets the number of rows to skip.

Example: Take
```js
DATA.find('products').take(10).callback(console.log);
```

### builder.page(page, [limit])

Type: `method`

Selects a page.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `Number` | yes |  | The page, from 1. |
| `limit` | `Number` | no |  | Rows per page. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Sets `skip` to `(page - 1) * take`. With `limit` it also sets `take` first.

Example: Page
```js
DATA.list('products').page(3, 20).callback(console.log);
```

### builder.paginate(page, limit, [maxlimit])

Type: `method`

Selects a page from untrusted values.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `Number|String` | yes |  | The page. |
| `limit` | `Number|String` | yes |  | Rows per page. |
| `maxlimit` | `Number` | no |  | The highest allowed limit. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Converts `page` and `limit` to numbers (strings from a query string work), uses page 1 when the page is missing, zero or negative, keeps the limit under `maxlimit` and uses `maxlimit` when no limit is given.

Example: From a query string
```js
DATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);
```

### builder.autoquery(query, schema, [defsort], [maxlimit])

Type: `method`

Builds fields, filters, sort and paging from a query string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `query` | `Object` | yes |  | The query string, usually `$.query`. |
| `schema` | `String` | yes |  | The allowed fields and types. |
| `defsort` | `String` | no |  | The default sort, for example `dtcreated_desc`. |
| `maxlimit` | `Number` | no |  | Enables paging with this highest limit. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

`schema` lists the allowed fields as `name:type` separated by commas (types: `string`, `number`, `date`, `boolean`, `[string]`, `json`; the default is `string`), or `@SchemaName` to take them from a JSON schema. `query.fields` selects among the allowed fields (all of them when it is missing), each allowed field is filtered with `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) sorts by allowed fields or `defsort` is used, and with `maxlimit` `query.page` and `query.limit` go to `paginate()`. Fields that are not in the schema are ignored. Columns selected with `fields()` before `autoquery()` stay selected, and the fields of the query string are added to them for this query only.

Example: A grid
```js
DATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);
```

### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])

Type: `method`

Builds fields, filters, sort and paging for properties of a JSON column.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action, or the query string. |
| `column` | `String` | yes |  | The JSON column. |
| `schema` | `String` | yes |  | The allowed properties and types. |
| `defsort` | `String` | no |  | The default sort, for example `weight_desc`. |
| `maxlimit` | `Number` | no |  | Enables paging with this highest limit. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Works like `autoquery()`, but the fields are properties stored in the JSON column `column`. `$` is the `$` of an action (its `query` is used) or the query string itself. `schema` lists the properties as `name:type` separated by commas (types: `string`, `number`, `boolean`, `date`, `[string]`; the default is `string`). The QueryBuilder gives the adapter each property as the name `json:column:property:type` in the fields, the filter and the sort, and the adapter translates it into its own syntax; the PostgreSQL adapter reads the property with `->>` and converts it to its type. `column` may contain only letters, digits and `_`, otherwise the method throws an error; properties with other characters are ignored. It can follow `autoquery()` on the same query.

Example: Columns and JSON properties
```js
DATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);
```

### builder.gridfilter(name, query, [type], [column])

Type: `method`

Adds a filter from a query string value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The key in `query`. |
| `query` | `Object` | yes |  | The query string. |
| `type` | `String` | no | `'string'` | The type of the value. |
| `column` | `String` | no |  | The column, when it differs from `name`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Reads `query[name]` and adds a condition by its form: `a - b` is `between`, `a,b` is an OR of searches for text and `in` for other types, `=a,b` is `in` with exact texts, `=a` an exact match, a plain text a `search`, `>v` and `<v` comparisons. For dates `today`, `yesterday` and a date select the whole day, a 4-digit number the year and a small number the month. `type` is `string`, `number`, `date`, `boolean`, `[string]` (array filter) or `json` (search). Empty values add nothing.

Example: Gridfilter
```js
DATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);
```

### builder.language(value, [prefix], [skip])

Type: `method`

Sets the language for localized columns.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes |  | The language or an object with `language`. |
| `prefix` | `String` | no |  | The prefix. |
| `skip` | `String` | no |  | A language that means "no language". |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Sets the option `language` to `prefix + value`. `value` can be an object with `language` (such as `$`). When `value` equals `skip` the language is empty. Without `prefix` and `skip` the defaults of `db.language()` apply. The `nosql` adapter replaces a trailing `§` in column names with the language.

Example: Language
```js
DATA.find('products').fields('id,name§').language($).callback($);
```

### builder.returning(fields)

Type: `method`

Asks the adapter to return columns of the changed rows.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | yes |  | For example `id,name`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

A comma-separated list stored in the option `returning`. With an upsert, an empty returned result means "nothing was updated".

Example: Returning
```js
DATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);
```

### builder.insert(fn, [param])

Type: `method`

Prepares the payload of an upsert insert.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `function(payload, param)`. |
| `param` | `Object` | no |  | A value passed to `fn`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

With `update(table, data, true)`, `fn(payload, param)` is called before the payload is inserted, so you can add values that only a new row needs.

Example: Upsert
```js
DATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {
	doc.id = 'home';
	doc.dtcreated = NOW;
}).callback(console.log);
```

### builder.error(message, [reverse])

Type: `method`

Turns an empty result into an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | The error, for example `@(User not found)`. |
| `reverse` | `Boolean` | no | `false` | Fail when there is a result. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

When the response is empty (no value, or an empty array for queries that do not take one row), the query fails with `message`. With `reverse` set to `true`, a non-empty response fails. Alias: `err()`.

Example: Not found
```js
DATA.read('users').id($.params.id).error('@(User not found)').callback($);
```

### builder.callback(fn)

Type: `method`

Sets the callback of the query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|$` | yes |  | `function(err, response)` or `$`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

`fn(err, response)` is called when the query finishes. Pass `$` of an action to answer the action with the result. Alias: `pipe()`. `data(fn)` sets a callback only for success (`fn(response)`) and `fail(fn)` one only for errors (`fn(err)`).

Example: Callback
```js
DATA.find('users').callback(function(err, response) {
	console.log(err, response);
});
```

### builder.promise([$])

Type: `method`

Returns a promise of the query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | The `$` of an action. |

Returns: `Promise`

Resolves with the response. On error the promise is rejected with the error (an error object of the adapter gets the name `QueryBuilder(table --> operation)`), or, with `$`, the error goes to `$.invalid()`.

Example: Await
```js
var user = await DATA.read('users').id('u1').promise($);
```

### builder.done($, fn, [param])

Type: `method`

Calls fn on success and $.invalid() on error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action. |
| `fn` | `Function` | yes |  | `function(response, param)`. |
| `param` | `Object` | no |  | A value passed to `fn`. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

On success `fn(response, param)` is called; an error goes to `$.invalid()`.

Example: Done
```js
DATA.read('users').id($.params.id).done($, function(user) {
	$.callback({ id: user.id, name: user.name });
});
```

### builder.audit($, [message], [type])

Type: `method`

Writes an audit record after success.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` of an action. |
| `message` | `String` | no |  | The message. |
| `type` | `String` | no |  | The type of the record. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

After a successful query, calls `$.audit(message, type)`. Placeholders such as `{data.name}` in the message are filled from the payload, `{user.name}` from the user.

Example: Audit
```js
DATA.insert('products', model).audit($, 'Created product {data.name}').callback($);
```

### builder.set(name)

Type: `method`

Stores the result under a key of the DB() response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The key. |

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

In a `DB()` chain the response becomes an object and this result is saved as `response[name]`. `nobind()` keeps the result out of the response completely.

Example: Set
```js
var db = DB();
db.read('users').id('u1').set('user');
db.count('orders').where('userid', 'u1').set('orders');
db.callback($);
```

### builder.debug()

Type: `method`

Sets the debug option of the query.

Returns: `QueryBuilder` The same QueryBuilder, for chaining.

Sets `debug = true` in the options, so an adapter that supports it can log the query. `primarykey(name)` and `schema(name)` set the options `primarykey` and `schema` in the same way, for adapters that use them.

Example: Debug
```js
DATA.find('users').debug().callback(console.log);
```
