Show example query output as:
Fork me on GitHub

Knex.js is a "batteries included" SQL query builder for Postgres, MySQL, MariaDB and SQLite3, designed to be flexible, portable, and fun to use. It features both traditional node style callbacks as well as a promise interface for cleaner async flow control, a stream interface, full featured query and schema builders, transaction support, connection pooling and standardized responses between different query clients and dialects.

The project is hosted on GitHub, and has a comprehensive test suite.

Knex is available for use under the MIT software license.

You can report bugs and discuss features on the GitHub issues page, add pages to the wiki or send tweets to @tgriesser.

Thanks to all of the great contributions to the project.

Special thanks to Taylor Otwell and his work on the Laravel Query Builder, from which much of the builder's code and syntax was originally derived.

Latest Release: 0.7.5 - Change Log

Current Develop — Travis Badge


Upgrading 0.6 -> 0.7

Should be a painless upgrade, the only breaking change should be "collate nocase" no longer used as the default order by in sqlite3 for performance reasons. If there are other issues, please open a ticket.

Upgrading 0.5 -> 0.6

Big and exciting improvements from the 0.5 release, the 0.6 release brings refactored internals, streams, the ability to properly inject & bind knex.raw statements throughout any queries, the ability to re-use existing snippets. If you were only using the publicly documented API, no major changes should be necessary. If you notice any issues, please open a ticket. For a full list of changes, see the entry in the change log.


Knex can be used as an SQL query builder in both Node.JS and the browser, limited to WebSQL's constraints (like the inability to drop tables or read schemas). Composing SQL queries in the browser for execution on the server is highly discouraged, as this can be the cause of serious security vulnerabilities. The browser builds outside of WebSQL are primarily for learning purposes - for example, you can pop open the console and build queries on this page using the pg, mysql, and sqlite3 objects.


The primary target environment for Knex is Node.js, you will need to install the knex library, and then install the appropriate database library: pg for PostgreSQL, mysql for MySQL or MariaDB, or sqlite3 for SQLite3.

$ npm install knex@0.7 --save

# Then add one of the following (adding a --save) flag:
$ npm install mysql
$ npm install mariasql
$ npm install pg
$ npm install sqlite3


The browser builds and pre-built dependencies can be found in the browser directory. View source on this page to see the browser builds in-action.

Initializing the Library

The knex module is itself a function which takes a configuration object for Knex, accepting a few parameters. The client parameter is required and determines which client adapter will be used with the library.

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : '',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'

The connection options are passed directly to the appropriate database client to create the connection, and may be either an object, or a connection string:

var pg = require('knex')({
  client: 'pg',
  connection: process.env.PG_CONNECTION_STRING

Note: When you use the SQLite3 adapter, there is a filename required, not a network connection. For example:

var knex = require('knex')({
  client: 'sqlite3',
  connection: {
    filename: "./mydb.sqlite"

You can also connect via an unix domain socket, which will ignore host and port.

var knex = require('knex')({
  client: 'mysql',
  connection: {
    socketPath     : '/path/to/socket.sock',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'

Initializing the library should normally only ever happen once in your application, as it creates a connection pool for the current database, you should use the instance returned from the initialize call throughout your library.


Passing a debug: true flag on your initialization object will turn on debugging for all queries.


The client created by the configuration initializes a connection pool, using the generic-pool-redux library. This connection pool has a default setting of a min: 2, max: 10 for the MySQL and PG libraries, and a single connection for sqlite3 (due to issues with utilizing multiple connections on a single file). To change the config settings for the pool, pass a pool option as one of the keys in the initialize block.

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : '',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  pool: {
    min: 0,
    max: 7

If you ever need to explicitly teardown the connection pool, you may use knex.destroy([callback]). You may use knex.destroy by passing a callback, or by chaining as a promise, just not both.


For convenience, the any migration configuration may be specified when initializing the library. Read the Migrations section for more information and a full list of configuration options.

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : '',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  migrations: {
    tableName: 'migrations'

Knex Query Builder

The heart of the library, the knex query builder is the interface used for building and executing standard SQL queries, such as select, insert, update, delete.

knexknex(tableName) / knex.[methodName]
The query builder starts off either by specifying a tableName you wish to query against, or by calling any method directly on the knex object. This kicks off a jQuery-like chain, with which you can call additional query builder methods as needed to construct the query, eventually calling any of the interface methods, to either convert toString, or execute the query with a promise, callback, or stream.[*columns])
Creates a select query, taking an optional array of columns for the query, eventually defaulting to * if none are specified when the query is built. The response of a select call will resolve with an array of objects selected from the database.'title', 'author', 'year').from('books')'books')
Allows for aliasing a subquery, taking the string you wish to name the current query. If the query is not a sub-query, it will be ignored.

knex.avg('sum_column1').from(function() {
  this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1')

Specifically set the columns to be selected on a select query, taking an array or a list of of column names.

knex.column('title', 'author', 'year').select().from('books')
knex.column(['title', 'author', 'year']).select().from('books')

from.from([tableName]) Alias: into, table
Specifies the table used in the current query, replacing the current table name if one has already been specified. This is typically used in the sub-queries performed in the advanced where or union methods.'*').from('users')

Where Clauses

Several methods exist to assist in dynamic where clauses. In many places functions may be used in place of values, constructing subqueries. In most places existing knex queries may be used to compose sub-queries, etc. Take a look at a few of the examples for each method for instruction on use:


Object Syntax:

  first_name: 'Test',
  last_name:  'User'

Key, Value:

knex('users').where('id', 1)

Grouped Chain:

knex('users').where(function() {
  this.where('id', 1).orWhere('id', '>', 10)
}).orWhere({name: 'Tester'})


knex('users').where('votes', '>', 100)
var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id');

knex('accounts').where('id', 'in', subquery)

whereIn.whereIn(column, array|callback|builder) / .orWhereIn
Shorthand for .where('id', 'in', obj), the .whereIn and .orWhereIn methods add a "where in" clause to the query. Click the "play" button below to see the queries.'name').from('users')
  .whereIn('id', [1, 2, 3])
  .orWhereIn('id', [4, 5, 6])'name').from('users')
  .whereIn('account_id', function() {'id').from('accounts');
var subquery ='id').from('accounts');'name').from('users')
  .whereIn('account_id', subquery)
  .where('name', '=', 'John')
  .orWhere(function() {
    this.where('votes', '>', 100).andWhere('title', '<>', 'Admin');

whereNotIn.whereNotIn(column, array|callback|builder) / .orWhereNotIn

knex('users').whereNotIn('id', [1, 2, 3])
knex('users').where('name', 'like', '%Test%').orWhereNotIn('id', [1, 2, 3])

whereNull.whereNull(column) / .orWhereNull


whereNotNull.whereNotNull(column) / .orWhereNotNull


whereExists.whereExists(builder | callback) / .orWhereExists

knex('users').whereExists(function() {'*').from('accounts').whereRaw('users.account_id =');
knex('users').whereExists('*').from('accounts').whereRaw('users.account_id ='))

whereNotExists.whereNotExists(builder | callback) / .orWhereNotExists

knex('users').whereNotExists(function() {'*').from('accounts').whereRaw('users.account_id =');
knex('users').whereNotExists('*').from('accounts').whereRaw('users.account_id ='))

whereBetween.whereBetween(column, range) / .orWhereBetween

knex('users').whereBetween('votes', [1, 100])

whereNotBetween.whereNotBetween(column, range) / .orWhereNotBetween

knex('users').whereNotBetween('votes', [1, 100])

whereRaw.whereRaw(query, [bindings])
Convenience helper for .where(knex.raw(query)).

knex('users').whereRaw('id = ?', [1])

Join Methods

Several methods are provided which assist in building joins.

join.join(table, first, [operator], second)
The join builder can be used to specify joins between tables, with the first argument being the joining table, the next three arguments being the first join column, the join operator and the second join column, respectively.

  .join('contacts', '', '=', 'contacts.user_id')
  .select('', '')
  .join('contacts', '', 'contacts.user_id')
  .select('', '')

For grouped joins, specify a function as the second argument for the join query, and use on and orOn to create joins that are grouped with parentheses.'*').from('users').join('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

If you need to use a literal value (string, number, or boolean) in a join instead of a column, use knex.raw.'*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin']));

innerJoin.innerJoin(column, ~mixed~)

knex.from('users').innerJoin('accounts', '', 'accounts.user_id')
knex.table('users').innerJoin('accounts', '', '=', 'accounts.user_id')
knex('users').innerJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

leftJoin.leftJoin(column, ~mixed~)'*').from('users').leftJoin('accounts', '', 'accounts.user_id')'*').from('users').leftJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

leftOuterJoin.leftOuterJoin(column, ~mixed~)'*').from('users').leftOuterJoin('accounts', '', 'accounts.user_id')'*').from('users').leftOuterJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

rightJoin.rightJoin(column, ~mixed~)'*').from('users').rightJoin('accounts', '', 'accounts.user_id')'*').from('users').rightJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

rightOuterJoin.rightOuterJoin(column, ~mixed~)'*').from('users').rightOuterJoin('accounts', '', 'accounts.user_id')'*').from('users').rightOuterJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

outerJoin.outerJoin(column, ~mixed~)'*').from('users').outerJoin('accounts', '', 'accounts.user_id')'*').from('users').outerJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

fullOuterJoin.fullOuterJoin(column, ~mixed~)'*').from('users').fullOuterJoin('accounts', '', 'accounts.user_id')'*').from('users').fullOuterJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

crossJoin.crossJoin(column, ~mixed~)'*').from('users').crossJoin('accounts', '', 'accounts.user_id')'*').from('users').crossJoin('accounts', function() {
  this.on('', '=', 'users.account_id').orOn('accounts.owner_id', '=', '')

joinRaw.joinRaw(sql, [bindings])'*').from('accounts').joinRaw('natural full join table1').where('id', 1)'*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1)

Sets a distinct clause on the query.

// select distinct 'first_name' from customers
  .distinct('first_name', 'last_name')

Adds a group by clause to the query.


Adds a raw group by clause to the query.'year', knex.raw('SUM(profit)')).from('sales').groupByRaw('year WITH ROLLUP')

orderBy.orderBy(column, [direction])
Adds an order by clause to the query.

knex('users').orderBy('name', 'desc')

Adds an order by raw clause to the query.'*').from('table').orderByRaw('col NULLS LAST DESC')

having.having(column, operator, value)
Adds a having clause to the query.

  .orderBy('name', 'desc')
  .having('count', '>', 100)

havingRaw.havingRaw(column, operator, value)
Adds a havingRaw clause to the query.

  .orderBy('name', 'desc')
  .havingRaw('count > ?', [100])

Adds an offset clause to the query.'*').from('users').offset(10)

Adds a limit clause to the query.'*').from('users').limit(10).offset(30)

union.union([*queries], [wrap])
Creates a union query, taking an array or a list of callbacks to build the union statement, with optional boolean wrap. The queries will be individually wrapped in parentheses with a true wrap parameter.'*').from('users').whereNull('last_name').union(function() {'*').from('users').whereNull('first_name');

Creates a union all query, with the same method signature as the union method.'*').from('users').whereNull('last_name').unionAll(function() {'*').from('users').whereNull('first_name');

insert.insert(data, [returning])
Creates an insert query, taking either a hash of properties to be inserted into the row, or an array of inserts, to be executed as a single insert command. Resolves the promise / fulfills the callback with an array containing the first insert id of the inserted model, or an array containing all inserted ids for postgresql.

// Returns [1] in "mysql", "sqlite"; [] in "postgresql" unless the 'returning' parameter is set.
knex('books').insert({title: 'Slaughterhouse Five'})
// Normalizes for empty keys on multi-row insert:
knex('coords').insert([{x: 20}, {y: 30},  {x: 10, y: 20}])
// Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id').into('books')

Only utilitzed by PostgreSQL databases, the returning method specifies which column should be returned by the insert and update methods.

// Returns [1]
  .insert({title: 'Slaughterhouse Five'})
// Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
  .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}])

update.update(data, [returning]) / .update(key, value, [returning])
Creates an update query, taking a hash of properties or a key/value pair to be updated based on the other query constraints. Resolves the promise / fulfills the callback with the number of affected rows for the query.

  .where('published_date', '<', 2000)
    status: 'archived'
// Returns [1] in "mysql", "sqlite"; [] in "postgresql" unless the 'returning' parameter is set.
knex('books').update('title', 'Slaughterhouse Five')

del / delete.del()
Aliased to del as delete is a reserved word in javascript, this method deletes one or more rows, based on other conditions specified in the query. Resolves the promise / fulfills the callback with the number of affected rows for the query.

  .where('activated', false)

Used by knex.transaction, the transacting method may be chained to any query and passed the object you wish to join the query as part of the transaction for.

var Promise = require('bluebird');

knex.transaction(function(trx) {

  knex('books').transacting(trx).insert({name: 'Old Books'})
    .then(function(resp) {
      var id = resp[0];
      return someExternalMethod(id, trx);

}).then(function(resp) {
  console.log('Transaction complete.');
}).catch(function(err) {

Dynamically added after a transaction is specified, the forUpdate adds a FOR UPDATE in PostgreSQL and MySQL during a select statement.


Dynamically added after a transaction is specified, the forShare adds a FOR SHARE in PostgreSQL and a LOCK IN SHARE MODE for MySQL during a select statement.


Performs a count on the specified column. Note that in Postgres, count returns a bigint type which will be a String and not a Number (more info).

knex('users').count('active as a')

Gets the minimum value for the specified column.

knex('users').min('age as a')

Gets the maximum value for the specified column.

knex('users').max('age as a')

Retrieve the sum of the values of a given column.

knex('users').sum('products as p')

Retrieve the average of the values of a given column.

knex('users').avg('age as a')

increment.increment(column, amount)
Increments a column value by the specified amount.

  .where('userid', '=', 1)
  .increment('balance', 10)

decrement.decrement(column, amount)
Decrements a column value by the specified amount.

knex('accounts').where('userid', '=', 1).decrement('balance', 5)

Truncates the current table.


This will pluck the specified column from each row in your results, yielding a promise which resolves to the array of values selected.

knex.table('users').pluck('id').then(function(ids) {

Similar to select, but only retrieves & resolves with the first record from the query.

knex.table('users').first('id', 'name').then(function(row) {

Clones the current query chain, useful for re-using partial query snippets in other queries without mutating the original.

Returns an object with the column info about the current table, or an individual column if one is passed, returning an object with the following keys:

knex('users').columnInfo().then(function(info) {
  // ...

Overrides the global debug setting for the current query chain. If enabled is omitted, query debugging will be turned on.

Explicitly specify the connection for the query, allowing you to use the knex chain outside of the built-in pooling capabilities.

Allows for mixing in additional options as defined by database client specific libraries:

knex('accounts as a1')
  .leftJoin('accounts as a2', function() {
    this.on('', '<>', '');
  .select(['', ''])
  .where(knex.raw(' = 1'))
  .option({ nestTables: true, rowMode: 'array' })


Transactions are an important feature of relational databases, as they allow correct recovery from failures and keep a database consistent even in cases of system failure. All queries within a transaction are executed on the same database connection, and run the entire set of queries as a single unit of work. Any failure will mean the database will rollback any queries executed on that connection to the pre-transaction state.

Transactions are handled by passing a handler function into knex.transaction. The handler function accepts a single argument, the an object which may be used in two ways:

  1. As the "promise aware" knex connection
  2. As an object passed into a query with and eventually call commit or rollback.
Consider these two examples:

var Promise = require('bluebird');

// Using trx as a query builder:
knex.transaction(function(trx) {

  var books = [
    {title: 'Canterbury Tales'},
    {title: 'Moby Dick'},
    {title: 'Hamlet'}

  return trx
    .insert({name: 'Old Books'}, 'id')
    .then(function(ids) {
      return, function(book) {
        book.catalogue_id = ids[0];

        // Some validation could take place here.

        return trx.insert(info).into('books');

.then(function(inserts) {
  console.log(inserts.length + ' new books saved.');
.catch(function(error) {
  // If we get here, that means that neither the 'Old Books' catalogues insert,
  // nor any of the books inserts will have taken place.

And then this example:

var Promise = require('bluebird');

// Using trx as a transaction object:
knex.transaction(function(trx) {

  var books = [
    {title: 'Canterbury Tales'},
    {title: 'Moby Dick'},
    {title: 'Hamlet'}

  knex.insert({name: 'Old Books'}, 'id')
    .then(function(ids) {
      return, function(book) {
        book.catalogue_id = ids[0];

        // Some validation could take place here.

        return knex.insert(info).into('books').transacting(trx);
.then(function(inserts) {
  console.log(inserts.length + ' new books saved.');
.catch(function(error) {
  // If we get here, that means that neither the 'Old Books' catalogues insert,
  // nor any of the books inserts will have taken place.

Notice that if a promise is not returned within the handler, it is up to you to ensure trx.commit, or trx.rollback are called, otherwise the transaction connection will hang.

Schema Builder

These methods return promises.

createTableknex.schema.createTable(tableName, callback)
Creates a new table on the database, with a callback function to modify the table's structure, using the schema-building commands.

knex.schema.createTable('users', function (table) {

renameTableknex.schema.renameTable(from, to)
Renames a table from a current tableName to another.

knex.schema.renameTable('users', 'old_users')

Drops a table, specified by tableName.


Checks for a table's existence by tableName, resolving with a boolean to signal if the table exists.

knex.schema.hasTable('users').then(function(exists) {
  if (!exists) {
    return knex.schema.createTable('users', function(t) {
      t.string('first_name', 100);
      t.string('last_name', 100);

hasColumnknex.schema.hasColumn(tableName, columnName)
Checks if a column exists in the current table, resolves the promise with a boolean, true if the column exists, false otherwise.

Drops a table conditionally if the table exists, specified by tableName.


tableknex.schema.table(tableName, callback)
Chooses a database table, and then modifies the table, using the Schema Building functions inside of the callback.

knex.schema.table('users', function (table) {

Run an arbitrary sql query in the schema builder chain.

knex.schema.raw("SET sql_mode='TRADITIONAL'")
  .table('users', function (table) {

Schema Building:

Drops a column, specified by the column's name

Drops multiple columns, taking a variable number of column names.

renameColumntable.renameColumn(from, to)
Renames a column from one name to another.

Adds an auto incrementing column, in PostgreSQL this is a serial. This will be used as the primary key for the column. Also available is a bigIncrements if you wish to add a bigint incrementing number (in PostgreSQL bigserial).

Adds an integer column.

In MySQL or PostgreSQL, adds a bigint column, otherwise adds a normal integer. Note that bigint data is returned as a string in queries because JavaScript may be unable to parse them without loss of precision.

texttable.text(name, [textType])
Adds a text column, with optional textType for MySql text datatype preference.
textType may be mediumtext or longtext, otherwise defaults to text.

stringtable.string(name, [length])
Adds a string column, with optional length defaulting to 255.

floattable.float(column, [precision], [scale])
Adds a float column, with optional precision and scale.

decimaltable.decimal(column, [precision], [scale])
Adds a decimal column, with optional precision and scale.

Adds a boolean column.
Adds a date column.

Adds a dateTime column.

Adds a time column.

timestamptable.timestamp(name, [standard])
Adds a timestamp column, defaults to timestamptz in PostgreSQL, unless true is passed as the second argument.
Note that the method for defaulting to the current datetime varies from one database to another. For example: PostreSQL requires .defaultTo(knex.raw('now()')), but SQLite3 requires .defaultTo(knex.raw("date('now')")).

Adds a created_at and updated_at column on the database, setting these each to dateTime types.

Adds a binary column.

enum / enutable.enu(col, values)
Adds a enum column, (aliased to enu, as enum is a reserved word in javascript).

jsontable.json(name, [jsonb])
Adds a json column, using the built-in json type in postgresql, defaulting to a text column in older versions of postgresql or in unsupported databases. jsonb can be used by passing true as the second argument.

Adds a uuid column - this uses the built-in uuid type in postgresql, and falling back to a char(36) in other databases.

Sets the comment for a table.

Sets the engine for the database table, only available within a createTable call, and only applicable to MySQL.

Sets the charset for the database table, only available within a createTable call, and only applicable to MySQL.

Sets the collation for the database table, only available within a createTable call, and only applicable to MySQL.

specificTypetable.specificType(column, value)
Sets a specific type for the column creation, if you'd like to add a column type that isn't supported here.

Chainable Methods:

The following three methods may be chained on the schema building methods, as modifiers to the column.

indexcolumn.index([indexName], [indexType])
Specifies an field as an index. If an indexName is specified, it is used in places of the standard index naming convention of tableName_columnName. The indexType can be optionally specified for PostgreSQL. No-op if this is chained off of a field that cannot be indexed.

Sets the field as the primary key for the table. To create a compound primary key, pass an array of column names: table.primary(['column1', 'column2']).

Sets the column as unique.

Sets the "column" that the current column references as a foreign key.

Sets the "table" where the foreign key column is located after calling column.references.

Sets the SQL command to be run "onDelete".

Sets the SQL command to be run "onUpdate".

Sets the default value for the column on an insert.

Specifies an integer as unsigned. No-op if this is chained off of a non-integer field.

Adds a not null on the current column being created.

Default on column creation, this explicitly sets a field to be nullable.

Sets the column to be inserted on the first position, only used in MySQL alter tables.

Sets the column to be inserted after another, only used in MySQL alter tables.

Sets the comment for a column.

knex.schema.createTable('accounts', function() {

Raw Queries

Sometimes you may need to use a raw expression in a query. Raw query object may be injected pretty much anywhere you want, and using proper bindings can ensure your values are escaped properly, preventing SQL-injection attacks.

Raw Expressions:

Raw expressions are created by using knex.raw(sql, [bindings]) and passing this as a value for any value in the query chain.

  .select(knex.raw('count(*) as user_count, status'))
  .orWhere(knex.raw('status <> ?', [1]))

Raw Queries:

The knex.raw may also be used to build a full query and execute it, as a standard query builder query would be executed. The benefit of this is that it uses the connection pool and provides a standard interface for the different client libraries.

knex.raw('select * from users where id = ?', [1]).then(function(resp) {

Note that the response will be whatever the underlying sql library would typically return on a normal query, so you may need to look at the documentation for the base library the queries are executing against to determine how to handle the response.

Wrapped Queries:

The raw query builder also comes with a wrap method, which allows wrapping the query in a value:

var subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no')
  .wrap('(', ') avg_sal_dept');'e.lastname', 'e.salary', subcolumn)
  .from('employee as e')
  .whereRaw('dept_no = e.dept_no')

Note that the example above be achieved more easily using the as method.

var subcolumn = knex.avg('salary')
  .whereRaw('dept_no = e.dept_no')
  .as('avg_sal_dept');'e.lastname', 'e.salary', subcolumn)
  .from('employee as e')
  .whereRaw('dept_no = e.dept_no')


Knex.js provides several options to deal with query output. The following methods are present on the query builder, schema builder, and the raw builder:


Promises are the preferred way of dealing with queries in knex, as they allow you to return values from a fulfillment handler, which in turn become the value of the promise. The main benefit of promises are the ability to catch thrown errors without crashing the node app, making your code behave like a .try / .catch / .finally in synchronous code.'name').from('users')
  .where('id', '>', 20)
  .andWhere('id', '<', 200)
  .then(function(rows) {
    return _.pluck(rows, 'name');
  .then(function(names) {
    return'id').from('nicknames').whereIn('nickname', names);
  .then(function(rows) {
  .catch(function(error) {

Coerces the current query builder chain into a promise state, accepting the resolve and reject handlers as specified by the Promises/A+ spec. As stated in the spec, more than one call to the then method for the current query chain will resolve with the same value, in the order they were called; the query will not be executed multiple times.'*').from('users').where({name: 'Tim'})
  .then(function(rows) {
    return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts');
  }).then(function(id) {
    console.log('Inserted Account ' + id);
  }).catch(function(error) {

Coerces the current query builder into a promise state, catching any error thrown by the query, the same as calling .then(null, onRejected).

return knex.insert({id: 1, name: 'Test'}, 'id').into('accounts')
  .catch(function(error) {
  }).then(function() {
    return'*').from('accounts').where('id', 1);
  }).then(function(rows) {
  }).catch(function(error) {

Executes side effects on the resolved response, ultimately returning a promise that fulfills with the original value. A thrown error or rejected promise will cause the promise to transition into a rejected state.

// Using only .then()
query.then(function(x) {
    return x;

// Using .tap()
A passthrough to Bluebird's map implementation with the result set.'name').from('users').limit(10).map(function(row) {
}).then(function(names) {
}).catch(function(e) {

reduce.reduce(reducer, [initialValue])
A passthrough to Bluebird's reduce implementation with the result set.'name').from('users').limit(10).reduce(function(memo, row) {
  return memo;
}, {count: 0, names: []}).then(function(obj) {
}).catch(function(e) {

A passthrough to Bluebird's bind method which sets the context value (this) for the returned promise.'name').from('users')

Shorthand for calling .then(function() { return value }).

// Without return:
  .then(function() {
    return {inserted: true};

knex.insert(values).into('users').return({inserted: true});


If you'd prefer a callback interface over promises, the exec function accepts a standard node style callback for executing the query chain. Note that as with the then method, subsequent calls to the same query chain will return the same result.'name').from('users')
  .where('id', '>', 20)
  .andWhere('id', '<', 200)
  .exec(function(err, rows) {
    if (err) return console.error(err);'id').from('nicknames').whereIn('nickname', _.pluck(rows, 'name'))
      .exec(function(err, rows) {
        if (err) return console.error(err);


Streams are a powerful way of piping data through as it comes in, rather than all at once. You can read more about streams here at substack's stream handbook. See the following for example uses of stream & pipe. If you wish to use streams with PostgreSQL, you must also install the pg-query-stream module. On an HTTP server, make sure to manually your streams if a request is aborted.[options], [callback])
If called with a callback, the callback is passed the stream and a promise is returned. Otherwise, the readable stream is returned.

// Retrieve the stream:
var stream ='*').from('users').stream();

// With options:
var stream ='*').from('users').stream({highWaterMark: 5});

// Use as a promise:
var stream ='*').from('users').where(knex.raw('id = ?', [1])).stream(function(stream) {
}).then(function() {
  // ...
}).catch(function(e) {

Pipe a stream for the current query to a writableStream.

var stream ='*').from('users').pipe(writableStream);


A query event is fired just before a query takes place, providing data about the query, including the connection's __cid property and any other information about the query as described in toSQL. Useful for logging all'*')
  .on('query', function(data) {
  .then(function() {
    // ...


Returns an array of query strings filled out with the correct values based on bindings, etc. Useful for debugging.'*').from('users').where(knex.raw('id = ?', [1])).toString()

Returns an array of query strings filled out with the correct values based on bindings, etc. Useful for debugging.'*').from('users').where(knex.raw('id = ?', [1])).toSQL()

// Ouputs:
  bindings: [1],
  method: 'select',
  sql: 'select * from "users" where id = ?',
  options: undefined,


Migrations allow for you to define sets of schema changes so upgrading a database is a breeze.

Migration CLI

The migration CLI is bundled with the knex install, and is driven by the node-liftoff module. To install globally, run:

$ npm install knex -g

The 0.6 migrations use a knexfile, which specify various configuration settings for the module. To create a new knexfile, run the following:

$ knex init

# or for .coffee

$ knex init -x coffee

will create a sample knexfile.js - the file which contains our various database configurations. Once you have a knexfile.js, you can use the migration tool to create migration files to the specified directory (default migrations). Creating new migration files can be achieved by running:

$ knex migrate:make migration_name

Once you have the migrations in place you wish to run, you can run:

$ knex migrate:latest

To update your database to the latest version.

Seed files

Seed files allow you to populate your database with test or seed data independent of your migration files.

Seed CLI

To create a seed file, run:

$ knex seed:make seed_name

Seed files are created in the directory specified in your knexfile.js for the current environment. A sample seed configuration looks like:

development: {
  client: ...,
  connection: { ... },
  seeds: {
      directory: './seeds/dev'

If no is defined, files are created in ./seeds. Note that the seed directory needs to be a relative path. Absolute paths are not supported (nor is it good practice).

To run seed files, execute:

$ knex seed:run

Seed files are executed in alphabetical order. Unlike migrations, every seed file will be executed when you run the command. You should design your seed files to reset tables as needed before inserting data.


A knexfile.js or generally contains all of the configuration for your database. It can optionally provide different configuration for different environments. You may pass a --knexfile option to any of the command line statements to specify an alternate path to your knexfile.

Basic configuration:

module.exports = {
  client: 'pg',
  connection: process.env.DATABASE_URL || {
    username: 'me',
    database: 'my_app'

Environment configuration:

module.exports = {
  development: {
    client: 'pg',
    connection: {
      username: 'me',
      database: 'my_app'
  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL

Migration API

knex.migrate is the class utilized by the knex migrations cli. Each method takes an optional config object, which may specify specifies the database, directory, extension, and tableName for the migrations.

makeknex.migrate.make(name, [config])
Creates a new migration, with the name of the migration being added.

Runs all migrations that have not yet been run.

Rolls back the latest migration group.

Retrieves and returns the current migration version, as a promise. If there aren't any migrations run yet, returns "none" as the value for the currentVersion.

Seed API

knex.seed is the class utilized by the knex seed CLI. Each method takes an optional config object, which may specify the relative directory for the migrations.

makeknex.seed.make(name, [config])
Creates a new seed file, with the name of the seed file being added.[config])
Runs all seed files for the current environment.


Have questions about the library? Come join us in the #bookshelf freenode IRC channel for support on knex.js and bookshelf.js, or post an issue on Stack Overflow or in the GitHub issue tracker.


How do I help contribute?
Glad you ask! Pull requests, or feature requests, though not always implemented, are a great way to help make Knex even better than it is now. If you're looking for something specific to help out with, there's a number of unit tests that aren't implemented yet, the library could never have too many of those. If you want to submit a fix or feature, take a look at the Contributing readme in the Github and go ahead and open a ticket.

How do I debug?
If you pass {debug: true} as one of the options in your initialize settings, you can see all of the query calls being made. Sometimes you need to dive a bit further into the various calls and see what all is going on behind the scenes. I'd recommend node-inspector, which allows you to debug code with debugger statements like you would in the browser.

At the start of your application code will catch any errors not otherwise caught in the normal promise chain handlers, which is very helpful in debugging.

How do I run the test suite?
The test suite looks for an environment variable called KNEX_TEST for the path to the database configuration. If you run the following command:

$ export KNEX_TEST='/path/to/your/knex_config.js'
$ npm test

replacing with the path to your config file, and the config file is valid, the test suite should run properly.

Can I use Knex outside of Node.js
Yes. While the WebSQL spec is deprecated, there is still an adapter that provides support. Checkout the browser builds for more details.

Change Log

0.7.5Mar 9, 2015

0.7.4Feb 25, 2015

0.7.3Oct 3, 2014

0.7.1 & 0.7.2Oct 1, 2014

0.7.0Oct 1, 2014
New Features:

Breaking Changes: Other Changes:

0.6.22July 10, 2014
Bug fix for properly binding postgresql streaming queries, (#363).

0.6.21July 9, 2014

0.6.20June 30, 2014
Allow case insensitive operators in sql clauses, (#344).

0.6.19June 27, 2014

0.6.18June 25, 2014
Patch for the method, calling without a handler should return the stream, not a promise (#337).

0.6.17June 23, 2014
Adding missing map / reduce proxies to bluebird's implementation.

0.6.16June 18, 2014

0.6.15June 14, 2014
Added the as method for aliasing subqueries.

0.6.14June 14, 2014
whereExists / whereNotExists may now take a query builder instance as well as a callback.

0.6.13June 12, 2014

0.6.12June 10, 2014
Fix for regression with boolean default types in PostgreSQL.

0.6.11June 10, 2014
Fix for regression with queries containing multiple order by statements in sqlite3.

0.6.10June 10, 2014
Fix for big regression in memoization of column names from 0.5 -> 0.6.

0.6.9June 9, 2014
Fix for regression in specificType method.

0.6.8June 9, 2014
Package.json fix for CLI.

0.6.7June 9, 2014

0.6.6June 9, 2014

0.6.5June 9, 2014
Add missing _ require to WebSQL builds.

0.6.4June 9, 2014
Fix & document schema.raw method.

0.6.3June 6, 2014

0.6.2June 4, 2014

0.6.1June 4, 2014
Reverting to using .npmignore, the "files" syntax forgot the knex.js file

0.6.0June 4, 2014
Major Library refactor. Notable changes & fixes include:

For More information, see this pull-request.

Show Full Change log