---
title: QueryBuilder
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/querybuilder/
updated: 2026-11-19T20:13:36.295Z
---

# QueryBuilder

> Query SQL databases with DATA, DB() and the QueryBuilder, and connect your database with an adapter registered by NEWDB().

Total.js 4 has a small, database-neutral **QueryBuilder** for SQL databases. You describe a query with chained methods (`find`, `where`, `sort`, `take`...) and the framework hands a plain description of it to an **adapter** that you register with `NEWDB()`. The adapter turns the description into SQL for your database and returns the rows. The framework itself does not ship an SQL driver: it ships the builder and the contract between the builder and the adapter.

## Register an adapter

`NEWDB([name], fn)` registers the adapter for a connection name. Without a name it is `default`. The name `*` is the fallback for every name that has no adapter of its own.

```js
// definitions/db.js
NEWDB(function(filter, callback) {
	// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'
	// filter.table  the table name
	// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]
	// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...
	mysqlbuilder(filter, function(err, rows) {
		callback(err, rows);
	});
});
```

The adapter calls `callback(err, response)` once. The shape of `response` depends on `filter.exec`:

| `exec` | What the adapter returns |
| --- | --- |
| `find` | An array of rows |
| `read`, `check` | An array (the framework keeps the first item, or `null`) or one row |
| `list` | `{ items: [...], count: Number }`. The framework adds `page`, `limit` and `pages` |
| `count`, `scalar` | A number or the aggregated value |
| `insert`, `update`, `remove` | The number of affected rows, or the rows of `returning` |
| `query`, `command` | Whatever the database returns |

All fields of `filter` are listed under *Adapter options* in the [reference](../../reference/querybuilder/). Register more databases with names, and pick them with a `name/` prefix in the table name:

```js
NEWDB('logs', function(filter, callback) { ... });

DATA.find('logs/requests').where('status', 500).callback(console.log);
```

## DATA and DB()

There are two ways to start a query:

- `DATA` is one global object. Each query you start on it runs on its own, at once. It is the fastest way for single queries.
- `DB()` (alias `DATABASE()`) creates a new controller. Its queries run **one after another**, and one final callback receives the result. When one query fails, the rest do not run.

```js
DATA.read('tbl_user').id(1).callback(function(err, user) {
	console.log(err, user);
});

var db = DB();
db.insert('tbl_order', { id: UID(), userid: 1, price: 50 });
db.update('tbl_user', { '+orders': 1 }).id(1);
db.callback(function(err, response) {
	// response is the response of the last query
});
```

On a `DB()` controller, `builder.set(name)` stores a response under a key of the final response instead of replacing it:

```js
var db = DB();
db.read('tbl_user').id(1).set('user');
db.find('tbl_order').where('userid', 1).set('orders');
db.callback(function(err, response) {
	// response.user, response.orders
});
```

Every method of `DB()` or `DATA` returns the builder of that query, so chain the filters on it. To add another query, call the controller again.

## Filters

```js
DATA.find('tbl_product')
	.fields('id,name,price')
	.where('isremoved', false)
	.where('price', '>', 10)
	.in('category', ['phones', 'tablets'])
	.search('name', 'iphone')
	.or(function(builder) {
		builder.where('stock', '>', 0);
		builder.where('ispreorder', true);
	})
	.sort('price', true)
	.take(20)
	.callback(console.log);
```

Each filter adds an object to `filter.filter`; the adapter decides how to write it in SQL. `where()` accepts the comparers `=`, `<>`, `>`, `<`, `>=` and `<=` (`==` becomes `=`, `!=` becomes `<>`). `sort(name, true)` sorts in descending order; the adapter receives `name_desc`.

## Inserting, updating and removing

```js
DATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });

DATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');

DATA.remove('tbl_user').id(id).callback(console.log);
```

The third argument of `update(table, data, true)` is **upsert**. When the update finds nothing, the framework calls the function from `builder.insert(fn)` (for example to add `dtcreated`) and runs the same data again as `insert`.

```js
DATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {
	model.count = 1;
	model.dtcreated = NOW;
});
```

How keys such as `+count` are written in SQL is up to the adapter.

## Raw SQL

`query([conn], sql, [params])` sends your own SQL to the adapter in `filter.query` and the arguments in `filter.params`. `DATA.query(sql, params)` uses the `default` connection when the second argument is an array or an object.

```js
DATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);
DATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);
```

## Errors, callbacks and promises

`builder.error(err)` turns an empty result (no row, or an empty array) into an error, a typical way to answer `404`. With `reverse` set to `true` it is the other way round: a found row is the error, which is useful for checks of duplicates.

In schemas and operations pass `$`: `callback($)` passes the error and the response to `$.callback`, `promise($)` sends an error to `$.invalid()`, and `done($, fn)` calls `fn(response)` only when there is no error.

```js
NEWSCHEMA('Users', function(schema) {
	schema.setRead(function($) {
		DATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);
	});
	schema.setRemove(async function($) {
		await DATA.check('tbl_user').id($.id).error('404').promise($);
		DATA.remove('tbl_user').id($.id).done($, () => $.success());
	});
});
```

## Lists for grids

`list()` returns one page of rows and the counts that a grid or a pager needs. `paginate(page, limit, maxlimit)` reads the values from the query string, and `autoquery()` builds the fields, filters, sort and paging from the query string by a list of allowed fields:

```js
schema.setQuery(function($) {
	DATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);
});
// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20
```

`gridfilter()` explains how one value of the query string becomes a filter: `10 - 50` is a range, `a,b` is a list, `>10` and `<10` compare, `!text` is an exact match and other text is a search.

## Schema shortcuts

`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` and `$ACTION` do not talk to a database. They run the operations of a schema by its name, and the schema usually calls `DATA` inside. They belong to [Schemas](../../guides/schemas/).
