{"id":15277432,"url":"https://github.com/kylefarris/node-querybuilder","last_synced_at":"2025-10-06T18:32:09.089Z","repository":{"id":10314475,"uuid":"12440733","full_name":"kylefarris/node-querybuilder","owner":"kylefarris","description":"Node QueryBuilder Adapter for Node.js (tags: nodejs, node, mysql, active record, activerecord, querybuilder, query builder)","archived":false,"fork":true,"pushed_at":"2023-05-14T18:09:27.000Z","size":6118,"stargazers_count":49,"open_issues_count":23,"forks_count":19,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-01-14T23:08:05.417Z","etag":null,"topics":["active-record","activerecord","mysql","node","nodejs","query-builder","querybuilder"],"latest_commit_sha":null,"homepage":"","language":"TSQL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"martintajur/node-mysql-activerecord","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kylefarris.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-08-28T17:55:47.000Z","updated_at":"2023-12-31T09:07:30.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/kylefarris/node-querybuilder","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kylefarris%2Fnode-querybuilder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kylefarris%2Fnode-querybuilder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kylefarris%2Fnode-querybuilder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kylefarris%2Fnode-querybuilder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kylefarris","download_url":"https://codeload.github.com/kylefarris/node-querybuilder/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235542253,"owners_count":19006820,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["active-record","activerecord","mysql","node","nodejs","query-builder","querybuilder"],"created_at":"2024-09-30T11:06:16.015Z","updated_at":"2025-10-06T18:32:03.691Z","avatar_url":"https://github.com/kylefarris.png","language":"TSQL","readme":"[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Node.js Version][node-image]][node-url]\n[![Build Status][travis-image]][travis-url]\n\n# Universal QueryBuilder for Node.js\nNode-QueryBuilder is an ambitious attempt to create a kind of \"universal translator\" which provides programmers a consistent API to connect to and query _any_ database (traditional and NoSQL) supported by the module. The module is highly extensible and, in theory, can suppport any database provided that the driver has been written for it.\n\nThe API of this module very closely mimics Codeigniter's Active Record (now called \"Query Builder\") library and much of the code has been directly translated from the PHP libraries in Codeigniter to JavaScript. A lot of credit needs to go to the folks over at EllisLab ([https://ellislab.com/codeigniter](https://ellislab.com/codeigniter)) and all the contributors to the Codeigniter project (of which I am one): [https://github.com/EllisLab/CodeIgniter/](https://github.com/EllisLab/CodeIgniter/)\n\nThe primary benefits of this module (currently) are:\n- Ability to write queries agnostically to the database you intend to query\n- Supports all basic database commands (insert, update, delete, select, etc...)\n- Extend capabilities from the most popular native database drivers in NPM.\n- Supports method chaining\n- Automatically escapes field values and identifiers by default\n- Is fully unit tested\n- **Very thoroughly documented**\n- Allows for greater flexibility and more control over a full ORM\n- Lighter-weight than an ORM\n- Allows you to drop down to the native methods of your driver if you choose to\n- Allows for different drivers for different versions (SQLite 2 vs SQLite 3)\n- The order in which you call the methods is irrelevant except for the execution methods (get, insert, update, delete) which must be called last.\n- Can used as a learning tool/Rosetta stone\n\n# Table of Contents\n- [Database Drivers](#database-drivers)\n- [How to Install](#how-to-install)\n- [License Info](#license-info)\n- [Quick Example](#quick-example)\n- [Connecting to Your Database](#connecting-to-your-database)\n  - [Quick Reference](#quick-reference)\n  - [Standard Connection Settings](#standard-connection-settings)\n  - [Choosing the Database Type](#choosing-the-database-type)\n  - [Choosing the Connection Type](#choosing-the-connection-type)\n  - [Managing Connections](#managing-connections)\n\n- [API Methods](#api-methods)\n  - [Chainable Methods](#chainable-methods)\n  - [Execution Methods](#execution-methods)\n    - [What Are Execution Methods?](#what-are-execution-methods)\n    - [Handling Error Messages and Results](#handling-error-messages-and-results)\n    - [Response Format Examples](#response-format-examples)\n  - [Other Library-Specific Methods](#other-library-specific-methods)\n\n- [Contribute](#contribute)\n\n# Database Drivers\n## Currently Written:\n- MySQL / MariaDB\n- Microsoft SQL Server\n\n## Coming Soon:\n- Postgres\n- Oracle\n- SQLite\n- MongoDB\n\n# How to install\n\n```\nnpm install node-querybuilder\n```\n\n# License Info\nLicensed under the GPL license and MIT:\n- [http://www.opensource.org/licenses/GPL-license.php](http://www.opensource.org/licenses/GPL-license.php)\n- [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)\n\n# Quick Example\nThis quick example shows how to connect to and asynchronously query a MySQL database using a pooled connection.\n\n```javascript\nconst QueryBuilder = require('node-querybuilder');\nconst settings = {\n    host: 'localhost',\n    database: 'mydatabase',\n    user: 'myuser',\n    password: 'MyP@ssw0rd'\n};\nconst pool = new QueryBuilder(settings, 'mysql', 'pool');\n\npool.get_connection(qb =\u003e {\n    qb.select('name', 'position')\n        .where({type: 'rocky', 'diameter \u003c': 12000})\n        .get('planets', (err, response) =\u003e {\n            qb.disconnect();\n\n            if (err) return console.error(\"Uh oh! Couldn't get results: \" + err.msg);\n\n            // SELECT `name`, `position` FROM `planets` WHERE `type` = 'rocky' AND `diameter` \u003c 12000\n            console.log(\"Query Ran: \" + qb.last_query());\n\n            // [{name: 'Mercury', position: 1}, {name: 'Mars', position: 4}]\n            console.log(\"Results:\", response);\n        }\n    );\n});\n```\n\nAnywhere a callback is used in the examples below, you can substitute for a Promise (or async/await). Here's the same code above in Promise format:\n\n```javascript\nconst QueryBuilder = require('node-querybuilder');\nconst settings = {\n    host: 'localhost',\n    database: 'mydatabase',\n    user: 'myuser',\n    password: 'MyP@ssw0rd'\n};\nconst pool = new QueryBuilder(settings, 'mysql', 'pool');\n\nasync function getPlanets() {\n    try {\n        const qb = await pool.get_connection();\n        const response = await qb.select('name', 'position')\n            .where({type: 'rocky', 'diameter \u003c': 12000})\n            .get('planets');\n\n        // SELECT `name`, `position` FROM `planets` WHERE `type` = 'rocky' AND `diameter` \u003c 12000\n        console.log(\"Query Ran: \" + qb.last_query());\n\n        // [{name: 'Mercury', position: 1}, {name: 'Mars', position: 4}]\n        console.log(\"Results:\", response);\n    } catch (err) {\n        return console.error(\"Uh oh! Couldn't get results: \" + err.msg);\n    } finally {\n        qb.disconnect();\n    }\n}\n\ngetPlanets();\n```\n\n# Connecting to Your Database\n## Quick Reference\n\nDriver                                     | Default  | Ready   | single | pool | cluster | Additional Connection Options\n:----------------------------------------- | :------- | :------ | :----- | :--- | :------ | :----------------------------------------------------------------------------------------\n[mysql](//www.npmjs.com/package/mysql)     | \u0026#x2713; | Yes     | Yes    | Yes  | Pending | [node-mysql connection options](https://github.com/felixge/node-mysql#connection-options)\n[mssql](//www.npmjs.com/package/tedious)   |          | Yes     | Yes    | Yes  | ???     | [tedious connection options](http://tediousjs.github.io/tedious/api-connection.html)\n[sqlite3](//www.npmjs.com/package/sqlite3) |          | No      | Yes    | ???  | ???     |\n[oracle](//www.npmjs.com/package/oracle)   |          | No      | Yes    | ???  | ???     |\n[postgres](//www.npmjs.com/package/pg)     |          | No      | Yes    | Yes  | ???     |\n[mongodb](//www.npmjs.com/package/mongodb) |          | No      | Yes    | ???  | ???     |\n\n## Standard Connection Settings\nThe options listed below are available for all database drivers. Additional properties may be passed if the driver of the database you are connecting to supports them. See the \"Additional Connection Options\" column above for a link to the a specific driver's connection options documentation.\n\nOption              | Default   | Optional | Description\n:------------------ | :-------- | :------- | :-------------------------------------------\n**host**            | localhost | No       | The server you're connecting to\n**user**            | NULL      | No       | The database user\n**password**        | NULL      | Yes      | The database `user`'s password\n**database**        | NULL      | Yes      | The database to connect to\n**port**            | NULL      | Yes      | The database port to use when connecting\n**pool_size**       | 10        | Yes      | Max connections for `pool` connection type\n**pool_min**        | 10        | Yes      | Min connections for `pool` connection type (`mssql` only)\n**acquireTimeout**  | 10000     | Yes      | The milliseconds before a timeout occurs during the connection acquisition.\n**debug**           | false     | Yes      | If true, debug info will be place in app log\n**version**         | default   | Yes      | Version of database driver to use\n\nThe best way to store these options is in a JSON file outsite of your web root where only root and the server user can access them.\n\n**Example JSON File**\n\nWe'll call this `db.json`.\n\n```javascript\n{\n    \"host\": \"db.myserver.com\",\n    \"user\": \"myusername\",\n    \"password\": \"P@s$w0rD\",\n    \"database\": \"myDB\",\n    \"pool_size\": 50\n}\n```\n\n**Example App**\n\n```javascript\nconst settings = require('db.json');\n// Second and third parameters of the QueryBuilder method default to 'mysql' and 'standard', respectively\nconst qb = new require('node-querybuilder')(settings);\n```\n\nOf course you can also just have a normal javascript object directly within your code somwhere if you're honing your inner Chuck Norris:\n\n**Chuck Norris App**\n\n```javascript\nconst qb = new require('node-querybuilder')({\n    host: 'db.myserver.com',\n    user: 'myusername',\n    password: 'P@s$w0rD',\n    database: 'MyDB',\n    pool_size: 50\n});\n```\n\n## Choosing the Database Type\nThis part is super simple. Just pass which one you'd like to use as the second parameter to the constructor (`mysql` is the default):\n\n**_Example:_**\n\n```javascript\nconst qb = new require('node-querybuilder')(settings, 'mssql');\n```\n\n## Choosing the Connection Type\nThis library currently supports 3 connection methods:\n- **_single_** (default)\n  - This will use the driver's basic single connection capabilities. All connections to your app will use this single database connection. This is usually less than ideal for most web applications but might be quite suitable for command line scripts and the like.\n  - **All drivers must have this connection type**.\n\n- **_pool_**\n  - This will utilize the driver's connection pooling capabilities if it is offered. Connection pooling allows your application to pull from a pool of connections that were created by the driver. Typically the connections will be handed out to requesting methods in a round-robin fashion. This is ideal for a web application.\n\n- **_cluster_**\n  - _NOTE: This feature is currently incomplete._\n  - When you have a cluster of servers and you want to create pools of connections to different servers to help load balance your stack, using the `cluster` connection type can come in handy. This is ideal for high-traffic web sites and applications that utilize a farm of database servers as opposed to just one.\n\n**Note:** You will specify the type of connection as the third parameter to the contructor\n\n**Example:**\n\n```javascript\nconst qb = new require('node-querybuilder')(settings, 'mysql', 'pool');\n```\n\n## Managing Connections\n\nIt's important to handle your connections properly. When not using a pool, for every connection you make, you'll need to disconnect it when you're done. If you're using a pool (or cluster), it's a similar concept... but you'll be _releasing_ the connection back to the pool so it can be used again later.\n\n**Single Connection Example:**\n\n```javascript\nconst qb = new require('node-querybuilder')(settings, 'mysql');\n\nqb.get('planets', (err, response) =\u003e {\n    // Disconnect right away unless you're going to use it again for subsequent query\n    qb.disconnect();\n\n    if (err) return console.error(err);\n    return console.log(\"Results: \", response);\n});\n```\n\n**Connection Pool Example:**\n\n```javascript\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\n// Get a connection (aka a QueryBuilder instance) from the pool\npool.get_connection(qb =\u003e {\n    qb.get('planets', (err, response) =\u003e {\n        // Release right away unless you're going to use it again for subsequent query\n        qb.release();\n\n        if (err) return console.error(err);\n        return console.log(\"Results: \", response);\n    });\n});\n```\n\n# API Methods\n**_NOTE:_** The compatibility portions of these tables are subject to change as features and drivers are written!\n\n## Chainable Methods\nChainable methods can be called as many times as you'd like in any order you like. The final query will not be built and executed until one of the [execution methods](#execution-methods), like `get()`,  are callled. As the name implies, the methods can be chained together indefinitely but this is not required. You definitely call them individually with the same effect at execution time.\n\nAPI Method                            | SQL Command | MySQL    | MSSQL    | Oracle   | SQLite   | Postgres | Mongo\n:------------------------------------ | :---------- | :------: | :------: | :------: | :------: | :------: | :------:\n[select()](#select)                   | SELECT      | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[distinct()](#distinct)               | DISTINCT    | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[select_min()](#min)                  | MIN         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[select_max()](#max)                  | MAX         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[select_avg()](#avg)                  | AVG         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[select_sum()](#sum)                  | SUM         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[from()](#from)                       | FROM        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[join()](#join)                       | JOIN        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[where()](#where)                     | WHERE       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[where_in()](#where_in)               | IN          | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[where_not_in()](#where_not_in)       | WHERE       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_where()](#or_where)               | WHERE       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_where_in()](#or_where_in)         | WHERE       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_where_not_in()](#or_where_not_in) | WHERE       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[like()](#like)                       | LIKE        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_like()](#or_like)                 | LIKE        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_not_like()](#or_not_like)         | LIKE        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[not_like()](#not_like)               | LIKE        | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[group_by()](#group-by)               | GROUP BY    | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[having()](#having)                   | HAVING      | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[or_having()](#or_having)             | HAVING      | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[order_by()](#order-by)               | ORDER BY    | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[limit()](#limit)                     | LIMIT       | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[offset()](#offset)                   | OFFSET      | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[set()](#set)                         | SET         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[returning()](#returning)             | OUTPUT      | \u0026#x2717; | \u0026#x2713; |          |          |          |\n\n--------------------------------------------------------------------------------\n\n### SELECT\n#### .select(fields[,escape])\nThis method is used to specify the fields to pull into the resultset when running SELECT-like queries.\n\nParameter | Type         | Default  | Description\n:-------- | :----------- | :------- | :--------------------------------------------\nfields    | String/Array | Required | The fields in which to grab from the database\nescape    | Boolean      | true     | TRUE: auto-escape fields; FALSE: don't escape\n\nThe fields provided to this method will be automatically escaped by the database driver. The `fields` parameter can be passed in 1 of 2 ways (field names will be trimmed in either scenario):\n\n**_NOTE:_** If the select method is never called before an execution method is ran, `SELECT *` will be assumed.\n- String with fields seperated by a comma:\n  - `.select('foo, bar, baz')`\n\n- Array of field names\n  - `.select(['foo', 'bar', 'baz'])`\n\n**Examples**\n\n```javascript\n// SELECT * FROM galaxies\nqb.select('*').get('foo', (err, results) =\u003e {});\n\n// Easier and same result:\nqb.get('foo', (err, results) =\u003e {});\n\n// Async/Await version:\nconst results = await qb.get('foo');\n\n```\n\nAn array of field names:\n\n```javascript\n// SELECT `foo`, `bar`, `baz`\nqb.select(['foo', 'bar', 'baz']);\n```\n\nYou can chain the method together using different patterns if you want:\n\n```javascript\n// SELECT `foo`, `bar`, `baz`, `this`, `that`, `the_other`\nqb.select(['foo', 'bar', 'baz']).select('this, that, the_other');\n```\n\nYou can alias your field names and they will be escaped properly as well:\n\n```javascript\n// SELECT `foo` as `f`, `bar` as `b`, `baz` as `z`\nqb.select(['foo as f', 'bar as b', 'baz as z']);\n```\n\nYou can optionally choose not to have the driver auto-escape the fieldnames (dangerous, but useful if you a utilize function in your select statement, for instance):\n\n```javascript\n// SELECT CONCAT(first_name,' ',last_name) AS `full_name`\nqb.select('CONCAT(first_name,' ',last_name) AS `full_name`', false);\n```\n\nIn order to successfully use subqueries in your select statements, you *must* supply `false` to the second parameter. _Please, for custom clauses containing subqueries, make sure you escape everything properly!_ **_ALSO NOTE:_** with this method, there may be conflicts between database drivers!\n\n```javascript\n// (SELECT `name` FROM `planets` WHERE `id`=8675309) AS `planet_name`\nqb.select('(SELECT `name` FROM `planets` WHERE `id`=8675309) AS `planet_name`', false);\n\n```\n\n**_NOTE:_** If you use this technique to add driver-specific functions, it may (and probably will) cause unexpected outcomes with other database drivers!\n\n--------------------------------------------------------------------------------\n\n### DISTINCT\n#### .distinct()\nThis SQL command is used to prevent duplicate rows from being returned in the resultset at the database level. It should only be used when querying data (execution methods: `.get()` \u0026 `.get_where()`) (not inserting, updating or removing). If it's provided to another execution method, it will simply be ignored.\n\n**_This method takes no parameters_**\n\n**Example**\n\n```javascript\n// SELECT DISTINCT `id`, `name`, `description` FROM `users`\nqb.distinct().select('id, name, description').get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### MIN\n#### .select_min(field[,alias])\nThis SQL command is used to find the minimum value for a specific field within a resultset.\n\nParameter | Type   | Default  | Description\n:-------- | :----- | :------- | :------------------------------------\nfield     | String | Required | The field to get the minimum value of\nalias     | String | NULL     | Optional alias to rename field\n\n**Examples**\n\n```javascript\n// SELECT MIN(`age`) FROM `users`\nqb.select_min('age').get('users', callback);\n```\n\nYou can optionally include a second parameter to rename the resulting field\n\n```javascript\n// SELECT MIN(`age`) AS `min_age` FROM `users`\nqb.select_min('age', 'min_age').get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### MAX\n#### .select_max(field[,alias])\nThis SQL command is used to find the maximum value for a specific field within a resultset.\n\nParameter | Type   | Default  | Description\n:-------- | :----- | :------- | :------------------------------------\nfield     | String | Required | The field to get the maximum value of\nalias     | String | NULL     | Optional alias to rename field\n\n**Examples**\n\n```javascript\n// SELECT MAX(`age`) FROM `users`\nqb.select_max('age').get('users', callback);\n```\n\nYou can optionally include a second parameter to rename the resulting field\n\n```javascript\n// SELECT MAX(`age`) AS `max_age` FROM `users`\nqb.select_max('age', 'max_age').get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### AVG\n#### .select_avg(field[,alias])\nThis SQL command is used to find the average value for a specific field within a resultset.\n\nParameter | Type   | Default  | Description\n:-------- | :----- | :------- | :------------------------------------\nfield     | String | Required | The field to get the average value of\nalias     | String | NULL     | Optional alias to rename field\n\n**Examples**\n\n```javascript\n// SELECT AVG(`age`) FROM `users`\nqb.select_avg('age').get('users', callback);\n```\n\nYou can optionally include a second parameter to rename the resulting field\n\n```javascript\n// SELECT AVG(`age`) AS `avg_age` FROM `users`\nqb.select_avg('age', 'avg_age').get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### SUM\n#### .select_sum(field[,alias])\nThis SQL command is used to find the minimum value for a specific field within a result set.\n\nParameter | Type   | Default  | Description\n:-------- | :----- | :------- | :------------------------------------\nfield     | String | Required | The field to get the minimum value of\nalias     | String | NULL     | Optional alias to rename field\n\n**Examples**\n\n```javascript\n// SELECT SUM(`age`) FROM `users`\nqb.select_sum('age').get('users', callback);\n```\n\nYou can optionally include a second parameter to rename the resulting field\n\n```javascript\n// SELECT SUM(`age`) AS `sum_age` FROM `users`\nqb.select_sum('age', 'sum_age').get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### FROM\n#### .from(tables)\nThis SQL command is used to determine which sources, available to the active connection, to obtain data from.\n\nParameter | Type         | Default  | Description\n:-------- | :----------- | :------- | :------------------------------------------\ntables    | String/Array | Required | Table(s), view(s), etc... to grab data from\n\nYou can provide tables, views, or any other valid source of data in a comma-separated list (string) or an array. When more than one data-source is provided when connected to a traditional RDMS, the tables will joined using a basic join. You can also `.from()` multiple times to get the same effect (the order in which they are called does not matter).\n\nAliases can be provided and they will be escaped properly.\n\n**_NOTE:_** You can also pass table/view names into the `.get()` and `.get_where()` methods and forego this method entirely.\n\n**Examples**\n\n**_Basic_**\n\n```javascript\n// SELECT `id`, `name`, `description` FROM `users`\nqb.select('id, name, description').from('users').get(callback);\n```\n\n**_Comma-Seperated_**\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `u`.`description`, `g`.`name` AS `group_name`\n// FROM (`users` `u`, `groups` `g`)\nqb.select('u.id, u.name, u, description, g.name as group_name')\n    .from('users u, groups g')\n    .get(callback);\n```\n\n**_Array of Tables_**\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `u`.`description`, `g`.`name` AS `group_name`\n// FROM (`users` `u`, `groups` `g`)\nqb.select('u.id, u.name, u, description, g.name as group_name')\n    .from(['users u', 'groups g'])\n    .get(callback);\n```\n\n**_Multiple From Calls_**\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `u`.`description`, `g`.`name` AS `group_name`\n// FROM (`users` `u`, `groups` `g`)\nqb.from('groups g').select('u.id, u.name, u, description, g.name as group_name')\n    .from('users u')\n    .get(callback);\n```\n\n--------------------------------------------------------------------------------\n\n### JOIN\n#### .join(table, relation[,direction])\nThis SQL command is used query multiple tables related and connected by keys and get a single result set.\n\nParameter | Type    | Default  | Description\n:-------- | :------ | :------- | :--------------------------------------------------\ntable     | String  | Required | The table or view to join to.\nrelation  | String  | Required | The \"ON\" statement that relates two tables together\ndirection | String  | \"left\"   | Direction of the join (see join types list below)\nescape    | Boolean | true     | TRUE: Escape table name and conditions; FALSE: No escaping\n\n**Join Types/Directions**\n- left\n- right\n- outer\n- inner\n- left outer\n- right outer\n\nThe table/view and the relationship of it to the main table/view (see: `.from()`) must be specified. The specific type of join defaults to \"left\" if none is specified (although it is recommended to always supply this value for readability). Multiple function calls can be made if you need several joins in one query. Aliases can (and should) be provided and they will be escaped properly.\n\n**Warning about complex relationship clauses**\nThis library currently does not support complex/nested ON clauses passed to the `relation` (second) parameter. You can supply multiple statements as long as they are not nested within parentheses. If you need to use a complex relationship clause, please make sure to escape those parts manually and pass `false` to the `escape` (fourth) parameter. See examples below for more details.\n\nIf anyone would like to add this capability, please submit a pull request!\n\n**Examples**\n\nIf no direction is specified, \"left\" will be used:\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `t`.`name` AS `type_name`\n// FROM `users` `u`\n// LEFT JOIN `types` `t` ON `t`.`id`=`u`.`type_id`\nqb.select('u.id, u.name, t.name as type_name').from('users u')\n    .join('types t', 't.id=u.type_id')\n    .get(callback);\n```\n\nYou may specify a direction:\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `t`.`name` AS `type_name`\n// FROM `users` `u`\n// RIGHT OUTER JOIN `types` `t` ON `t`.`id`=`u`.`type_id`\nqb.select('u.id, u.name, t.name as type_name').from('users u')\n    .join('types t', 't.id=u.type_id', 'right outer')\n    .get(callback);\n```\n\nMultiple function calls can be made if you need several joins in one query:\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `t`.`name`  AS `type`, `l`.`name` AS `location`\n// FROM `users` `u`\n// LEFT JOIN `types` `t` ON `t`.`id`=`u`.`type_id`\n// LEFT JOIN `locations` `l` ON `l`.`id`=`u`.`location_id`\nconst select = ['u.id', 'u.name', 't.name as type', 'l.name as location'];\nqb.select(select).from('users u')\n    .join('types t', 't.id=u.type_id', 'right outer')\n    .join('locations l', 'l.id=u.location_id', 'left')\n    .get(callback);\n```\n\nIf you have a very complex condition you can choose to forego escaping (not recommended unless\nyou know what you're doing). NOTE: Please make sure to escape values manually.\n\n```javascript\n// SELECT `u`.`id`, `u`.`name`, `t`.`name`  AS `type`\n// FROM `users` `u`\n// LEFT JOIN `user_meta` `um` ON\n//   CASE\n//     WHEN `u`.`id` = 4132 THEN `um`.`id` = `um`.`userId`\n//     WHEN `u`.`name` = 4132 THEN `um`.`name` = `u`.`id`\nconst select = ['u.id', 'u.name', 'um.name as user_name'];\nconst user_data = req.body;\nqb.select(select).from('users u')\n    .join('`user_meta` `um`', 'CASE WHEN `u`.`id` = ' + user_data.id  + ' THEN `um`.`id` = `um`.`userId` WHEN `u`.`name` = ' + user_data.id + ' THEN `um`.`name` = `u`.`id`', 'right outer', false)\n    .get(callback);\n```\n\n--------------------------------------------------------------------------------\n\n### WHERE\nThis SQL command is used to limit the resultset based on filters.\n\nParameter     | Type          | Default  | Description\n:------------ | :------------ | :------- | :------------------------------------------------------------\nfield/filters | String/Object | Required | A field name, a WHERE clause, or an object of key/value pairs\nvalue         | Mixed         | N/A      | When the first parameter is a field name, this is the value\nescape        | Boolean       | TRUE     | TRUE: Escape field names and values; FALSE: No escaping\n\n#### .where(field[,value[,escape]])\nThis method can be called in many different ways depending on your style and the format of the data that you have at the time of calling it. For standard SQL, all clauses will be joined with 'AND'—if you need to join clauses by 'OR', please us `.or_where()`. By default, all values and field names passed to this function will be escaped automatically to produce safer queries. You can turn this off by passing **false** into the third parameter.\n\nIf a valid field name is passed in the first parameter, you can pass an array the second parameter and the call will be treated as a [.where_in()](#where_in).\n\n**Examples**\n\nIf you just want to pass a single filter at a time:\n\n```javascript\n// SELECT `galaxy` FROM `universe` WHERE `planet_name` = 'Earth'\nqb.select('galaxy').where('planet_name', 'Earth').get('universe', callback);\n```\n\nIf you need more complex filtering using different operators (`\u003c, \u003e, \u003c=, =\u003e, !=, \u003c\u003e, etc...`), you can simply provide that operator along with the key in the first parameter. The '=' is assumed if a custom operator is not passed:\n\n```javascript\n// SELECT `planet` FROM `planets` WHERE `order` \u003c= 3\nqb.select('planet').where('order \u003c=', 3).get('planets', callback);\n```\n\nYou can conveniently pass an object of key:value pairs (which can also contain custom operators):\n\n```javascript\n// SELECT `planet` FROM `planets` WHERE `order` \u003c= 3 AND `class` = 'M'\nqb.select('planet').where({'order \u003c=':3, class:'M'}).get('planets', callback);\n```\n\nYou can construct complex WHERE clauses manually and they will be escaped properly as long as there are no parenthesis within it. _Please, for custom clauses containing subqueries, make sure you escape everything properly!_ **_ALSO NOTE:_** with this method, there may be conflicts between database drivers!\n\n```javascript\n// SELECT `planet` FROM `planets` WHERE `order` \u003c= 3 AND `class` = 'M'\nqb.select('planet').where(\"order \u003c= 3 AND class = 'M'\").get('planets', callback);\n```\n\nYou can pass a non-empty array as a value and that portion will be treated as a call to `.where_in()`:\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `planet_count` \u003e= 4, `star` IN('Sun', 'Betelgeuse')\nqb.select('star_system')\n    .where({'planet_count \u003e=': 4, star: ['Sun', 'Betelgeuse']})\n    .get('star_systems', callback);\n```\n\n\u003ca name=\"or_where\"\u003e\u003c/a\u003e\n\n#### .or_where(field[,value[,escape]])\nThis method functions identically to [.where()](#where) except that it joins clauses with 'OR' instead of 'AND'.\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `star` = 'Sun' OR `star` = 'Betelgeuse'\nqb.select('star_system').where('star', 'Sun')\n    .or_where('star', 'Betelgeuse')\n    .get('star_systems', callback);\n```\n\n\u003ca name=\"where_in\"\u003e\u003c/a\u003e\n\n#### .where_in(field, values[,escape])\nThis will create a \"WHERE IN\" statement in traditional SQL which is useful when you're trying to find rows with fields matching many different values... It will be joined with existing \"WHERE\" statements with 'AND'.\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `star` IN('Sun', 'Betelgeuse', 'Sirius', 'Vega', 'Alpha Centauri')\nconst stars = ['Sun', 'Betelgeuse', 'Sirius', 'Vega', 'Alpha Centauri'];\nqb.select('star_system').where_in('star', stars).get('star_systems', callback);\n```\n\n\u003ca name=\"or_where_in\"\u003e\u003c/a\u003e\n\n#### .or_where_in(field, values[,escape])\nSame as `.where_in()` except the clauses are joined by 'OR'.\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `planet_count` = 4 OR `star` IN('Sun', 'Betelgeuse')\nconst stars = ['Sun', 'Betelgeuse'];\nqb.select('star_system').where('planet_count', 4)\n    .or_where_in('star', stars)\n    .get('star_systems', callback);\n```\n\n\u003ca name=\"where_not_in\"\u003e\u003c/a\u003e\n\n#### .where_not_in(field, values[,escape])\nSame as `.where_in()` except this generates a \"WHERE NOT IN\" statement. All clauses are joined with 'AND'.\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `star` NOT IN('Sun', 'Betelgeuse', 'Sirius', 'Vega', 'Alpha Centauri')\nconst stars = ['Sun', 'Betelgeuse', 'Sirius', 'Vega', 'Alpha Centauri'];\nqb.select('star_system').where_not_in('star', stars).get('star_systems', callback);\n```\n\n\u003ca name=\"or_where_not_in\"\u003e\u003c/a\u003e\n\n#### .or_where_not_in(field, values[,escape])\nSame as `.where_not_in()` except that clauses are joined with 'OR'.\n\n```javascript\n// SELECT `star_system` FROM `star_systems`\n// WHERE `star` NOT IN('Sun', 'Betelgeuse')\n// OR `planet_count` NOT IN [2,4,6,8]\nconst stars = ['Sun', 'Betelgeuse'];\nconst planet_sizes = [2,4,6,8];\nqb.select('star_system')\n    .where_not_in('star', stars)\n    .or_where_not_in('planet_size', planet_sizes)\n    .get('star_systems', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### LIKE\nThis SQL command is used to find close matches where as the \"WHERE\" command is for precise matches. This is useful for doing searches.\n\nParameter     | Type          | Default  | Description\n:------------ | :------------ | :------- | :-------------------------------------------------\nfield/filters | String/Object | Required | Field name or object of field/match pairs\nvalue         | String/Number | Required | The value you want the field to closely match\nside          | String        | 'both'   | before: '%value'; after: 'value%', both: '%value%'\n\n**NOTE:** You can, alternatively, use `'right'` and `'left'` in place of `'before'` and '`after`' if you prefer.\n\n#### .like(field, match[,side])\nAll fields are escaped automatically, no exceptions. Multiple calls will be joined together with 'AND'. You can also pass an object of field/match pairs. Wildcard sides are interchangeable between before/left and after/right--choose the one that makes the most sense to you (there are examples of each below).\n\n**Examples**\n\nBy default, the match string will be wrapped on both sides with the wildcard (%):\n\n```javascript\n// SELECT `first_name` FROM `users` WHERE `first_name` LIKE '%mber%'\n// Potential results: [{first_name: 'Kimberly'},{first_name: 'Amber'}]\nqb.select('first_name').like('first_name', 'mber').get('users', callback);\n```\n\nYou can specify a side to place the wildcard (%) on if you'd like (before/left, after/right, both):\n\n```javascript\n// SELECT `first_name` FROM `users` WHERE `first_name` LIKE '%mber'\n// Potential results: [{first_name: 'Amber'}]\nqb.select('first_name').like('first_name', 'mber', 'before').get('users', callback);\n\n// SELECT `first_name` FROM `users` WHERE `first_name` LIKE 'Kim%'\n// Potential results: [{first_name: 'Kim'},{first_name: 'Kimberly'}]\nqb.select('first_name').like('first_name', 'Kim', 'right').get('users', callback);\n```\n\nYou can also pass 'none' if you don't want to use the wildcard (%)\n\n```javascript\n// SELECT `first_name` FROM `users` WHERE `first_name` LIKE 'kim'\n// Potential results: [{first_name: 'Kim'}]\nqb.select('first_name').like('first_name', 'kim', 'none').get('users', callback);\n```\n\nIf you'd like to have multiple like clauses, you can do that by calling like multiple times:\n\n```javascript\n// SELECT `first_name` FROM `users`\n// WHERE `first_name` LIKE 'Kim%'\n// AND `middle_name` LIKE '%lyt%'\n// AND `last_name` LIKE '%arris'\nqb.select('first_name')\n    .like('first_name', 'Kim', 'right')\n    .like('middle_name', 'lyt')\n    .like('last_name', 'arris', 'left')\n    .get('users', callback);\n```\n\nOr you can do it with an object of field/match pairs. If you want to pass a wildcard side, provide `null` as the second parameter and the side as the third. **Note**: All `match` values in an object will share the same wildcard side.\n\n```javascript\n// SELECT `first_name` FROM `users`\n// WHERE `first_name` LIKE '%ly'\n// AND `middle_name` LIKE '%the'\n// AND `last_name` LIKE '%is'\nqb.select('first_name')\n    .like({first_name: 'ly', middle_name: 'the', last_name: 'is'}, null, 'before')\n    .get('users', callback);\n```\n\n\u003ca name=\"or_like\"\u003e\u003c/a\u003e\n\n#### .or_like(field, match[,side])\nThis is exactly the same as the `.like()` method except that the clauses are joined by 'OR' not 'AND'.\n\n**Example**\n\n```javascript\n// SELECT `first_name` FROM `users`\n// WHERE `first_name` LIKE 'Kim%'\n// OR `middle_name` LIKE '%lyt%'\n// OR `last_name` LIKE '%arris'\nqb.select('first_name')\n    .or_like('first_name', 'Kim', 'right')\n    .or_like('middle_name', 'lyt')\n    .or_like('last_name', 'arris', 'left')\n    .get('users', callback);\n```\n\n\u003ca name=\"not_like\"\u003e\u003c/a\u003e\n\n#### .not_like(field, match[,side])\nThis is exactly the same as the `.like()` method except that it creates \"NOT LIKE\" statements.\n\n**Example**\n\n```javascript\n// SELECT `first_name` FROM `users`\n// WHERE `first_name` NOT LIKE 'A%'\n// AND `middle_name` NOT LIKE 'B%'\n// AND `last_name` NOT LIKE 'C%'\nqb.select('first_name')\n    .not_like({first_name: 'A', middle_name: 'B', last_name: 'C'}, null, 'after')\n    .get('users', callback);\n```\n\n\u003ca name=\"or_not_like\"\u003e\u003c/a\u003e\n\n#### .or_not_like(field, match[,side])\nThis is exactly the same as the `.not_like()` method except that the clauses are joined by 'OR' not 'AND'.\n\n**Example**\n\n```javascript\n// SELECT `first_name` FROM `users`\n// WHERE `first_name` NOT LIKE 'A%'\n// OR `middle_name` NOT LIKE 'B%'\n// OR `last_name` NOT LIKE 'C%'\nqb.select('first_name')\n    .or_not_like({first_name: 'A', middle_name: 'B', last_name: 'C'}, null, 'after')\n    .get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### GROUP BY\n#### .group_by(fields)\nThis SQL command allows you to get the first (depending on ORDER) result of a group of results related by a shared value or values.\n\nParameter | Type          | Default  | Description\n:-------- | :------------ | :------- | :---------------------------------\nfield(s)  | String/Object | Required | Field name or array of field names\n\n**Examples**\n\nGroup by a single field:\n\n```javascript\n// SELECT * FROM `users` GROUP BY `department_id`\nqb.group_by('department_id').get('users', callback);\n```\n\nGroup by multiple fields:\n\n```javascript\n// SELECT * FROM `users` GROUP BY `department_id`, `position_id`\nqb.group_by(['department_id', 'position_id']).get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### HAVING\n#### .having(field, value)\nThis SQL command is similar to the 'WHERE' command but is used when aggregate functions are used in the \"SELECT\" portion of the query.\n\nParameter     | Type          | Default  | Description\n:------------ | :------------ | :------- | :-----------------------------------------------------\nfield/filters | String/Object | Required | Field name or object of field/value pairs to filter on\nvalue         | Mixed         | NULL     | Value to filter by\nescape        | Boolean       | true     | TRUE: Escape fields and values; FALSE: Don't escape.\n\nThis method works exactly the same way as the `.where()` method works with the exception of the fact that there is no 'HAVING' equivalent to 'WHERE IN'. See the [.where()](#where) documentation if you need additional information.\n\n**Examples**\n\nIf you just want to add a single having clause:\n\n```javascript\n// SELECT COUNT(*) AS `num_planets` FROM `star_systems`\n// GROUP BY `id`\n// HAVING `num_planets` = 5\nqb.group_by('id').having('num_planets', 5).count('star_systems', callback);\n```\n\nIf you need more complex filtering using different operators (`\u003c, \u003e, \u003c=, =\u003e, !=, \u003c\u003e, etc...`), you can simply provide that operator along with the key in the first parameter. The '=' is assumed if a custom operator is not passed:\n\n```javascript\n// SELECT COUNT(*) AS `num_planets` FROM `star_systems`\n// GROUP BY `id`\n// HAVING `num_planets` \u003e 5\nqb.group_by('id').having('num_planets \u003e', 5).count('star_systems', callback);\n```\n\nYou can conveniently pass an object of key:value pairs (which can also contain custom operators):\n\n```javascript\n// SELECT COUNT(*) AS `num_planets` FROM `star_systems`\n// GROUP BY `id`\n// HAVING `num_planets` \u003e 5\nqb.group_by('id').having({'num_planets \u003e': 5}).count('star_systems', callback);\n```\n\nYou can construct complex WHERE clauses manually and they will be escaped properly. _Please, for custom clauses containing subqueries, make sure you escape everything properly!_ **_ALSO NOTE:_** with this method, there may be conflicts between database drivers!\n\n```javascript\n// SELECT COUNT(*) AS `num_planets` FROM `star_systems`\n// GROUP BY `id`\n// HAVING `num_planets` \u003e (5+2)\nqb.group_by('id').having(\"`num_planets` \u003e (5+2)\", null, false).count('star_systems', callback);\n```\n\n\u003ca name=\"or_having\"\u003e\u003c/a\u003e\n\n#### .or_having(field[,value[,escape]])\nThis method functions identically to [.having()](#having) except that it joins clauses with 'OR' instead of 'AND'.\n\n```javascript\n// SELECT SUM(planets) AS `num_planets`, SUM(moons) AS `num_moons` FROM `star_systems`\n// GROUP BY `id`\n// HAVING `num_planets` \u003e= 5 OR `num_moons` \u003c= 10\nqb.group_by('id')\n    .having('num_planets \u003e=', 5)\n    .or_having('num_moons \u003c=', 10)\n    .count('star_systems', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### ORDER BY\n#### .order_by(field[,direction])\nThis SQL command is used to order the resultset by a field or fields in descending, ascending, or random order(s).\n\nParameter | Type         | Default  | Description\n:-------- | :----------- | :------- | :----------------------------------------------------------------------\nfields    | String/Array | Required | Field name or an array of field names, possibly with directions as well\ndirection | String       | 'asc'    | 'asc': Ascending; 'desc': Descending; 'rand'/'random'/'rand()': Random.\n\nThis is a very flexible method, offering a wide variety of ways you can call it. Variations include:\n- Pass the field name and omit the direction\n- Pass the field name and the direction as the first and second parameters, respectively (most common)\n- Pass an array of fields to first parameter, direction to second parameter.\n- Pass an array of fields + directions in first parameter and omit the second one.\n- Pass an array of fields (+ directions for some to override second parameter) to first parameter, direction to second parameter.\n- Pass a raw comma-separated string of field + directions in first parameter and omit the second one.\n\n**Examples**\n\nPass the field name and omit the direction\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` ASC\nqb.order_by('galaxy_name').get('galaxies', callback);\n```\n\nRandom sort\n\n```javascript\n// (MySQL) SELECT * FROM `galaxies` ORDER BY RAND() ASC\n// (MSSQL) SELECT * FROM `galaxies` ORDER BY NEWID() ASC\nqb.order_by('random').get('galaxies', callback);\n```\n\nPass the field name and the direction as the first and second parameters, respectively\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` DESC\nqb.order_by('galaxy_name', 'desc').get('galaxies', callback);\n```\n\nPass an array of fields to first parameter, direction to second parameter\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` DESC, `galaxy_size` DESC\nqb.order_by(['galaxy_name', 'galaxy_size'],'desc').get('galaxies', callback);\n```\n\nPass an array of fields + directions in first parameter and ommit the second one.\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` DESC, `galaxy_size` ASC\nqb.order_by(['galaxy_name desc', 'galaxy_size asc']).get('galaxies', callback);\n```\n\nPass an array of fields (+ directions for some to override second parameter) to first parameter, direction to second parameter\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` DESC, `galaxy_size` ASC\nqb.order_by(['galaxy_name desc', 'galaxy_size'],'asc').get('galaxies', callback);\n```\n\nPass a raw comma-separated string of field + directions in first parameter and omit the second one.\n\n```javascript\n// SELECT * FROM `galaxies` ORDER BY `galaxy_name` ASC, `galaxy_size` DESC\nqb.order_by('galaxy_name asc, galaxy_size desc').get('galaxies', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### LIMIT\n#### .limit(limit_to, offset)\nThis SQL command is used to limit a result set to a maximum number of results, regardless of the actual number of results that might be returned by a non-limited query.\n\nParameter | Type    | Default  | Description\n:-------- | :------ | :------- | :-----------------------------------------------------\nlimit_to  | Integer | Required | The maximum number of results you want from the query\noffset    | Integer | NULL     | Optional offset value (where to start before limiting)\n\n**Example**\n\n```javascript\n// SELECT * FROM `users` LIMIT 5\nqb.limit(5).get('users', callback);\n```\n\nYou can provide an option offset value instead of calling [.offset()](#offset) separately:\n\n```javascript\n// SELECT * FROM `users` LIMIT 5, 5\nqb.limit(5, 5).get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### OFFSET\n#### .offset(offset)\nThis SQL command is tell the \"LIMIT\" where to start grabbing data. If cannot be used without a limit having been set first.\n\nParameter | Type    | Default | Description\n:-------- | :------ | :------ | :-----------------------------\noffset    | Integer | NULL    | where to start before limiting\n\nThe practical uses of this method are probably miniscule since the `.limit()` method must be called in order to use it and the limit method provides a means by which to set the offset. In any case, the method is very simple: pass the result row index that you want to start from when limiting. This is most useful for pagination of search results and similar scenarios.\n\n**Example**\n\n```javascript\n// SELECT * FROM `users` LIMIT 5, 25\nqb.limit(5).offset(25).get('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### SET\n#### .set(key[, value[, escape]])\nThis SQL is used to set values to fields when utilizing the `update`, and `insert` methods. More than likely, you will choose use the shorthand notation provided by the aforementioned methods, but, this can be handy in some cases.\n\nParameter | Type          | Default  | Description\n:-------- | :------------ | :------- | :-----------------------------------------------------------------------------------------------------\nkey       | String/Object | Required | The key of field to be set or an object of key:value pairs\nvalue     | Mixed         | NULL     | Required if `key` is a string. Pass NULL if `key` is an object and you'd like to use the 3rd parameter\nescape    | String/Object | true     | If false, keys and values will not be escaped.\n\n**Examples**\n\nBasic single setting of a value\n\n```javascript\n// UPDATE `users` SET `birthday` = '2015-02-04'\nqb.set('birthday','2015-02-04').update('users', callback);\n```\n\nSet multiple keys and values at once\n\n```javascript\nconst birthday = new Date(1986, 7, 5, 8, 15, 23);\n// UPDATE `users` SET `birthday` = '2015-02-04', `anniversary` = '2010-05-15'\nqb.set({birthday: birthday, anniversary: '2010-05-15'}).update('users', callback);\n```\n\n--------------------------------------------------------------------------------\n\n### RETURNING / OUTPUT\n#### .returning(id)\nThis method is required for MSSQL when performing INSERT queries to get the IDs of the row(s) that were inserted. You should supply which column(s) should be returned by the INSERT query as the `insert_id` in the response object. If you need multiple values (compound primary key, for instance) you can supply an array of strings representing those columns. If you call this method while using the `mysql` driver, it will be ignored silently.\n\nParameter | Type          | Default  | Description\n:-------- | :------------ | :------- | :-----------------------------------------------------------------------------------------------------\nkey       | String/Array  | Required | The ID or IDs used to identify the row that you're inserting\n\n**How This Works**\n\nUpon a successful `INSERT` query, you will be provided with a `result` object (see: [Response Format Examples](#response-format-examples)). I the `returning()` method is not called when using the MSSQL driver, the `insert_id` property of the result object will be `NULL`. This is not needed for the MySQL driver because its engine already supplies this info to the driver by default.\n\n**Examples**\n\nBasic single ID example\n\n```javascript\n// INSERT INTO [users] ([first_name], [last_name]) OUTPUT INSERTED.[id] VALUES ('John', 'Smith')\nqb.returning('id').insert('users', {first_name: 'John', last_name: 'Smith'});\n```\n\nReturn multiple column that should act as the `insert_id`\n\n```javascript\n// INSERT INTO [users] ([position_request_id], [job_id], [name], [title]) OUTPUT INSERTED.[position_request_id], INSERTED.[job_id] VALUES (42, 1337, 'John Smith', 'Hacker')\nqb.returning(['position_request_id', 'job_id']).insert('applicants', {position_request_id: 42, job_id: 1337, name: 'John Smith', title: 'Hacker'});\n```\n\n--------------------------------------------------------------------------------\n\n## Execution Methods\n\nAPI Method                        | SQL Command   | MySQL    | MSSQL    | Oracle | SQLite | Postgres | Mongo\n:-------------------------------- | :------------ | :------: | :------: | :----: | :----: | :------: | :---:\n[query()](#query)                 | N/A           | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[get()](#get)                     | N/A           | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[get_where()](#get_where)         | N/A           | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[count()](#count)                 | COUNT         | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[update()](#update)               | UPDATE        | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[update_batch()](#update_batch)   | N/A           | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[insert()](#insert)               | INSERT        | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[insert_batch()](#insert_batch)   | N/A           | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[insert_ignore()](#insert-ignore) | INSERT IGNORE | \u0026#x2713; | \u0026#x2717; |        |        |          |\n[delete()](#delete)               | DELETE        | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[truncate()](#truncate)           | TRUNCATE      | \u0026#x2713; | \u0026#x2713; |        |        |          |\n[empty_table()](#empty_table)     | DELETE        | \u0026#x2713; | \u0026#x2713; |        |        |          |\n\n### What are \"Execution Methods\"??\nExecution methods are the end-of-chain methods in the QueryBuilder library. Once these methods are called, all the chainable methods you've called up until this point will be compiled into a query string and sent to the driver's `query()` method. At this point, the QueryBuilder will be reset and ready to build a new query. The database driver will respond with results depending on the type of query being executed or with an error message.\n\n### Handling Error Messages and Results\n\n#### Callback Style\nThe final parameter of every execution method will be a callback function. If a callback is supplied to that final parameter, a Promise object *WILL NOT* be returned.\n\nThe parameters for the callback are in the `node.js` standard `(err, response)` format. If the driver throws an error, a JavaScript `Standard Error` object will be passed into the `err` parameter. The `response` parameter can be supplied with an array of result rows (`.get()` \u0026 `.get_where()`), an integer (`.count()`), or a response object containing rows effected, last insert id, etc... in any other scenario.\n\n#### Promise Style\nIf a callback function is not supplied to the final parameter of execution methods, a Promise will be returned. If the driver throws an error a JavaScript `Standard Error` object will be sent to the the Promise's `reject` callback parameter. The `response` will be sent to the Promise's `resolve` callback parameter. The `response` can be an array of result rows (`.get()` \u0026 `.get_where()`), an integer (`.count()`), or a response object containing rows effected, last insert id, etc... in any other scenario.\n\nObviously, `async/await` is supported through this style.\n\n### Response Format Examples\n\nAPI Method(s)                  | Response Format\n:----------------------------- | :-----------------------------------------------------------------------------------------\nget(), get_where()             | `[{field:value,field2:value2},{field:value, field2:value2}]`\ncount()                        | Integer (ex. `578`)\ninsert(), update(), delete()   | Example: `{insert_id: 579, affected_rows: 1, changed_rows: 0 [,and others per DB driver]}`\ninsert_batch(), update_batch() | Example: `{insert_id: 579, affected_rows: 1, changed_rows: 0 [,and others per DB driver]}`\n\n**NOTE**\n\nWhen using the [returning()](#returning) method with compatible drivers (`mssql`), the `insert_id` property of the response object will be an array of objects containing key value pairs representing the requested \"returned\" columns along with their values.\n\nExample:\n\n```javascript\n// results: {insert_id: [{id: 12345}], affected_rows: 1, changed_rows: 0}\nconst results = await qb.returning('id').insert('users', {firstName: 'John', lastName: 'Smith'});\n```\n\n#### Callback Example\n\n```javascript\npool.get_connection(qb =\u003e qb.get('foo', (err, response) =\u003e {\n    qb.release();\n    if (err) return console.error(err);\n    response.forEach((v) =\u003e /* Do Something */);\n}));\n```\n\n#### Promise Example\n\n**Note:** Don't do it this way. It's silly, verbose, and out-dated.\n\n```javascript\npool.get_connection().then(qb =\u003e {\n    const result = qb.get('foo');\n    qb.release();\n    return result;\n}).then(response =\u003e {\n    response.forEach((v) =\u003e /* Do Something */);\n    return response;\n}).catch(err =\u003e{\n    return console.error(err);\n});\n```\n\n#### Async/Await Example\n\n```javascript\nasync function getFoo() {\n    let qb;\n    try {\n        qb = await pool.get_connection();\n        const response = qb.get('foo');\n        response.forEach((v) =\u003e /* Do Something */);\n    } catch (err) {\n        console.error(err);\n    } finally {\n        if (qb) qb.release();\n    }\n}\n\ngetFoo();\n```\n\n#### Using the Same Connection Pool Connection for Successive Calls\n\nThis is an ideal scenario for the async/await pattern.\n\n```javascript\nconst pool = new require('node-querybuilder')(settings,'mysql','pool');\nconst data = {first_name: 'John', last_name: 'Smith'};\n\nasync function addUser() {\n    let qb;\n    try {\n        qb = await pool.get_connection();\n        const results = await qb.insert('users', data);\n\n        if (results.affected_rows === 1) {\n            const user = await qb.get_where('users', {id: res.insert_id});\n            console.log('New User: ', user);\n        } else {\n            throw new Error(\"New user was not added to database!\");\n        }\n    } catch (err) {\n        console.error(err);\n    } finally {\n        if (qb) qb.release();\n    }\n}\n\nupdateUser();\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"query\"\u003e\u003c/a\u003e\n\n### .query(query_string[, callback])\n\nParameter    | Type     | Default   | Description\n:----------- | :------- | :-------- | :---------------------------------------------\nquery_string | String   | Required  | Query to send directly to your database driver\ncallback     | Function | undefined | (optional) What to do when the driver has responded\n\n*****This method bypasses the entire QueryBuilder portion of this module***** is simply uses your database driver's native querying method. You should be cautious when using this as none of this module's security and escaping functionality will be utilized.\n\nThere are scenarios when using this method may be required; for instance, if you need to run a very specific type of command on your database that is not typical of a standard, CRUD-type query (ex. user permissions or creating a view).\n\n**Example**\n\n```javascript\nconst sql = qb.select(['f.foo', 'b.bar'])\n    .from('foo f')\n    .join('bar b', 'b.foo_id=f.id', 'left')\n    .get_compiled_select();\n\nqb.query(\"CREATE VIEW `foobar` AS \" + sql, callback);\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get\"\u003e\u003c/a\u003e\n\n### .get([table[,callback]])\n\nParameter | Type     | Default    | Description\n:-------- | :------- | :--------- | :------------------------------------------------------------\ntable     | String   | undefined  | (optional) Used to avoid having to call `.from()` seperately.\ncallback  | Function | undefined  | (optional) What to do when the driver has responded\n\nThis method is used when running queries that might respond with rows of data (namely, \"SELECT\" statements...). You can pass a table name as the first parameter to avoid having to call [.from()](#from) separately. If the table name is omitted, and the first parameter is a callback function, there will be no need to pass a callback function into the second parameter.\n\n**Response Type**\n\nArray of rows/records\n\n**Examples**\n\nIf you want to provide a table name into the first parameter:\n\n```javascript\n// SELECT * FROM `galaxies`\nqb.get('galaxies', callback);\n```\n\nIf you already have the table added to the query:\n\n```javascript\n// SELECT * FROM `galaxies`\nqb.from('galaxies').get(callback);\n```\n\nJust a more-complicated example for the sake of it:\n\n```javascript\n/**\n * SELECT\n *    `g`.`name`,\n *    `g`.`diameter`,\n *    `g`.`type_id`,\n *    `gt`.`name` AS `type`,\n *    COUNT(`s`.`id`) as `num_stars`\n * FROM `galaxies` `g`\n * LEFT JOIN `galaxy_types` `gt` ON `gt`.`id`=`g`.`type_id`\n * LEFT JOIN `stars` `s` ON `s`.`galaxy_id`=`g`.`id`\n * GROUP BY `g`.`id`\n * ORDER BY `g`.`name` ASC\n * LIMIT 10\n **/\nqb.limit(10)\n    .select(['g.name', 'g.diameter', 'gt.name as type'])\n    .select('COUNT(`s`.`id`) as `num_stars`',null,false)\n    .from('galaxies g')\n    .join('galaxy_types gt', 'gt.id=g.type_id', 'left')\n    .join('stars s', 's.galaxy_id=g.id', 'left')\n    .group_by('g.id')\n    .order_by('g.name', 'asc')\n    .get((err, response) =\u003e {\n        if (err) return console.error(err);\n\n        response.forEach(row =\u003e {\n            console.log(`The ${row.name} is a ${row.diameter} lightyear-wide ${row.type} galaxy with ${row.num_stars} stars.`);\n        });\n    });\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_where\"\u003e\u003c/a\u003e\n\n### .get_where(table, where[, callback])\n\nParameter | Type            | Default   | Description\n:-------- | :-------------- | :-------- | :-------------------------------------------------\ntable     | String or Array | Required  | Used to avoid having to call `.from()` separately.\nwhere     | Object          | Required  | Used to avoid having to call `.where()` separately\ncallback  | Function        | undefined | (optional) What to do when the driver has responded.\n\nThis method is basically the same as the `.get()` method except that if offers an additional shortcut parameter to provide a list of filters (`{field_name:value}`)  to limit the results by (effectively a shortcut to avoid calling `.where()` separately).  The other difference is that _all_ parameters are required and they must be in the proper order.\n\n**Response Type**\n\nArray of objects representing the result rows.\n\n**Examples**\n\nBasic example:\n\n```javascript\n// SELECT * FROM `galaxies` WHERE `num_stars` \u003e 100000000\nqb.get_where('galaxies', {'num_stars \u003e': 100000000}, callback);\n```\n\nYou can still provide other where statements if you want—they'll all work happily together:\n\n```javascript\n// SELECT * FROM `galaxies` WHERE `num_stars` \u003e 100000000 AND `galaxy_type_id` = 3\nqb.where('num_stars \u003e', 100000000).get_where('galaxies', {galaxy_type_id: 3}, callback);\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"count\"\u003e\u003c/a\u003e\n\n### .count([[table[, callback]])\n\nParameter | Type     | Default    | Description\n:-------- | :------- | :--------- | :------------------------------------------------------------\ntable     | String   | undefined  | (optional) Used to avoid having to call `.from()` separately.\ncallback  | Function | undefined  | (optional) What to do when the driver has responded.\n\nThis method is used to determine the total number of results that a query would return without actually returning the entire resultset back to this module. Obviously, you could simply execute the same query with `.get()` and then check the `length` property of the response array, but, that would take significantly more time and memory for very large resultsets.\n\nThe field in the resultset will always labeled be 'numrows'.\n\n**Response Type**\n\nInteger\n\n**Examples**\n\n```javascript\n// SELECT COUNT(*) AS `numrows` FROM `galaxies` WHERE `type` = 3\nconst type = 3;\nqb.where('type', type).count('galaxies', (err, count) =\u003e {\n    if (err) return console.error(err);\n    console.log(\"There are \" + numrows + \" Type \" + type + \" galaxies in the Universe.\");\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"update\"\u003e\u003c/a\u003e\n\n### .update(table, data[,where][, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :----------------------------------------------------------------------------------------------------\ntable     | String   | null      | (suggested) The table/collection you'd like to update\ndata      | Object   | null      | (suggested) The data to update (ex. `{field: value}`)\nwhere     | Object   | null      | (optional) Used to avoid having to call `.where()` separately. Pass NULL if you don't want to use it.\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nThis method is used to update a table (SQL) or collection (NoSQL) with new data. All identifiers and values are escaped automatically when applicable. The response parameter of the callback should receive a response object with information like the number of records updated, and the number of changed rows...\n\n**NOTE:**\n\nThe first and second parameters are not required but I do suggest you use them as your code will be much easier to read. If you choose not to use them, you will need to pass a \"falsey\" value to each... you can't simply skip them. My recommendation is to use `null`. The way you would supply these values without using this method would be through the `from()` method for the first parameter and the `set()` method for the second parameter.\n\n**Response Type**\n\nObject containing information about the results of the query.\n\n**Examples**\n\nHere's a contrived example of how it might be used in an app made with the Express framework:\n\n```javascript\nconst express = require('express');\nconst app = express();\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\napp.post('/update_account', (req, res) =\u003e {\n    const user_id = req.session.user_id;\n    const sanitize_name = name =\u003e name.replace(/[^A-Za-z0-9\\s'-]+$/,'').trim();\n    const sanitize_age = age =\u003e age.replace(/[^0-9]+$/,'').trim();\n\n    const data = {\n        first_name: sanitize_name(req.body.first_name),\n        last_name: sanitize_name(req.body.last_name),\n        age: sanitize_age(req.body.last_name),\n        bio: req.body.bio,\n    };\n\n    pool.get_connection(qb =\u003e {\n        qb.update('users', data, {id:user_id}, (err, res) =\u003e {\n            qb.release();\n            if (err) return console.error(err);\n\n            const page_data = {\n                prefill: data,\n            }\n            return res.render('/account_updated', page_data);\n        });\n    });\n});\n```\n\nHere's another (more-direct) example where one decided to supply the table, data, and filters through alternative methods:\n\n```javascript\nconst qb = new require('node-querybuilder')(settings, 'mysql', 'single');\nqb.where('id', 42)\n    .from('users')\n    .set('email', 'email@domain.net')\n    .update(null, null, null, (err, res) =\u003e {\n        if (err) return console.error(err);\n        console.log(\"Updated: \" + res.affected_rows + \" rows\");\n    });\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"update_batch\"\u003e\u003c/a\u003e\n\n### .update_batch(table, dataset, index[,where][, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :----------------------------------------------------------------------------------------------------\ntable     | String   | Required  | The table/collection you'd like to insert into\ndataset   | Array    | Required  | An array of data (rows) to update (ex. `[{id: 3, field: value}, {id: 4, field: val}]`)\nindex     | String   | Required  | Name of the key in each data object that represents a `where` clause.\nwhere     | Object   | NULL      | (optional) Used to avoid having to call `.where()` separately. Pass NULL if you don't want to use it.\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nThis method is a somewhat-complex one and, when using transactional databases, a bit pointless. Nevertheless, this will allow you to update a batch of rows with one query which, in theory, should be faster than running multiple update queries.\n\nThe important thing to understand is that there are, essentially, _two_ `where` clause portions with this method: a local one, and a global one. The `index` you specify in the 3rd parameter represents the name of the key in each data object of the dataset that will act as the local `where` clause for that particular row to be updated. That row, however, will only be updated if the global where clause(s) (4th param) have been satisfied as well.\n\n**NOTE:** This method will create batches of up to 100 rows at a time. So, if you have 250 rows to update, this will make 3 queries to your database.\n\n**Example:**\n\n```javascript\nconst qb =  new require('node-querybuilder')(settings, 'mysql', 'single');\n\n// The key to use as the local where clause\nconst key = 'id';\n\n// All objects in this dataset must have an id key\nconst dataset = [\n    {id: 4569, name: 'Cartwheel', constellation: 'Sculptor'},\n    {id: 5631, name: 'Black Eye', constellation: 'Coma Berenices'},\n    {id: 1238, name: 'Sombrero',  constellation: 'Virgo'}\n];\n\nconst where = {'last_updated \u003c' : '2015-01-01'}\n\nqb.update_batch('galaxies', dataset, key, where, (err, res) =\u003e {\n    if (err) return console.error(err);\n\n    /*\n     * UPDATE `galaxies`\n     * SET\n     * `name` = CASE\n     *      WHEN `id` = 4569 THEN 'Cartwheel'\n     *      WHEN `id` = 5631 THEN 'Black Eye'\n     *      WHEN `id` = 1238 THEN 'Sombrero'\n     *      ELSE `name`\n     * END,\n     * `constellation` = CASE\n     *      WHEN `id` = 4569 THEN 'Sculptor'\n     *      WHEN `id` = 5631 THEN 'Coma Berenices'\n     *      WHEN `id` = 1238 THEN 'Virgo'\n     *      ELSE `constellation`\n     * END\n     * WHERE `id` IN(4569, 5631, 1238)\n     * AND `last_updated` \u003c '2015-01-01'\n     */\n    const last_query = qb.last_query();\n});\n```\n\nAs you can see, in each `CASE` statement, the `key` and it's value are being used to determine what to set the other items to. It's important to know that the `key` and it's `value` will not be updated in the batch update... they are just there to make sure we set the right values in the right place.\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"insert\"\u003e\u003c/a\u003e\n\n### .insert(table, data[,ignore[,on_dupe]][, callback])\n\nParameter | Type     | Default    | Description\n:-------- | :------- | :--------- | :--------------------------------------------------------------------------------------------------------------\ntable     | String   | Required   | The table/collection you'd like to insert into\ndata      | Object   | Required   | The data to insert (ex. `{field: value}`)\nignore    | Boolean  | false      | (optional) If TRUE, generates IGNORE syntax for your driver if it's supported; ignored (haha) if not supported.\non_dupe   | String   | undefined  | (optional) Query suffix needed for generating an 'upsert' (ex. `ON DUPLICATE KEY UPDATE ...`).\ncallback  | Function | undefined  | (optional) What to do when the driver has responded.\n\nThis method is used to insert new data into a table (SQL) or collection (NoSQL). All identifiers and values are escaped automatically when applicable. The response parameter of the callback (or the Promise resolution value) should receive a response object with information like the ID of the newly inserted item, the affected rows (should be 1), etc...\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Examples**\n\nHere's a contrived example of how it might be used in an app made with the Express framework:\n\n```javascript\nconst express = require('express');\nconst app = express();\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\napp.post('/add_article', (req, res) =\u003e {\n    const user_id = req.session.user_id;\n\n    const data = {\n        title: req.body.first_name,\n        body: req.body.last_name,\n        author: user_id,\n        publish_date: sanitize_age(req.body.last_name)\n    };\n\n    pool.get_connection(qb =\u003e {\n        qb.insert('articles', data, (err, res) =\u003e {\n            qb.release();\n            if (err) return console.error(err);\n\n            const page_data = {\n                article_id: res.insert_id,\n            }\n            return res.render('/article_manager', page_data);\n        });\n    });\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"insert_batch\"\u003e\u003c/a\u003e\n\n### .insert_batch(table, dataset[,ignore[,on_dupe]][, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :------------------------------------------------------------------------------------------------------------------\ntable     | String   | Required  | The table/collection you'd like to delete records from.\ndataset   | Array    | undefined | An array of objects containing the data you want to insert. Pass *can* pass an empty array if you want to be silly.\nignore    | Boolean  | false     | (optional) If TRUE, generates IGNORE syntax for your driver if it's supported; ignored (haha) if not supported.\non_dupe   | String   | undefined | (optional) Query suffix needed for generating an 'upsert' (ex. `ON DUPLICATE KEY UPDATE ...`).\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nThe goal of this method is to speed the insertion of many rows. For instance, if you were insert 1,000 rows... Instead of making 1,000 queries to the server, you could just call `insert_batch()` and it would generate a single query to insert 1,000 rows. This is _much_ more efficient and less taxing on your app and database server.\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Example**\n\n```javascript\nconst qb = new require('node-querybuilder')(settings, 'mysql');\n\nconst data = [\n    {name: 'MySQL', version: '5.5.40'},\n    {name: 'Mongo', version: '2.6.7' },\n    {name: 'Postgres', version: '8.4'}\n];\n\nqb.insert_batch('db_engines', data, (err, res) =\u003e {\n    if (err) throw err;\n\n    // INSERT INTO `db_engines` (`name`, `version`)\n    // VALUES ('MySQL', '5.5.40'), ('Mongo', '2.6.7'), ('Postgres', '8.4');\n    console.log(qb.last_query());\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"insert_ignore\"\u003e\u003c/a\u003e\n\n### .insert_ignore(table, data[,on_dupe][, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :------------------------------------------------------------------------------------------------------------------\ntable     | String   | Required  | The table/collection you'd like to delete records from.\ndata      | Object   | undefined | An array of objects containing the data you want to insert. Pass *can* pass an empty array if you want to be silly.\non_dupe   | String   | undefined | (optional) Query suffix needed for generating an 'upsert' (ex. `ON DUPLICATE KEY UPDATE ...`).\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nThis method is just a wrapper to the `insert()` method which passes `true` to the ignore parameter. The purpose of using `IGNORE` syntax, for the drivers that support it, is so that a row insertion will be skipped if it's an exact duplicate of another row in the database. Optionally, you can provide a 3rd parameter containing a query that will update specified keys in the case of a duplicate entry (instead of simply ignoring it). With the third parameter, you can create an 'upsert' of sorts. Without the third parameter, it's essentially just \"ignoring\" errors, or, rather, converting them to simple warnings.\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Example**\n\n```javascript\n/*\n * Current Table Structure:\n *\n * [\n *        {name: 'MySQL', version: '5.5.40', last_modified: 1423252221 },\n *        {name: 'Mongo', version: '2.6.7',  last_modified: 1423252232 },\n *        {name: 'Postgres', version: '8.4', last_modified: 1423252248 }\n *    ]\n */\n\nconst qb = new require('node-querybuilder')(settings, 'mysql');\nconst data = {name: 'Postgres', version: '8.4'};\nqb.insert_ignore('db_engines', data, (err, res) =\u003e {\n    if (err) throw err;\n\n    // INSERT IGNORE INTO `db_engines` (`name`, `version`) VALUES ('Postgres', '8.4');\n    console.log(qb.last_query());\n\n    // 0 (because this data already exists...)\n    console.log(res.affected_rows);\n});\n```\n\nThis time we'll do it with an `on_dupe` string\n\n```javascript\nconst data = {name: 'Postgres', version: '8.4'};\nqb.insert_ignore('db_engines', data, 'ON DUPLICATE KEY UPDATE last_modified = NOW()', (err, res) =\u003e {\n    if (err) throw err;\n\n    // INSERT IGNORE INTO `db_engines` (`name`, `version`) VALUES ('Postgres', '8.4') ON DUPLICATE KEY UPDATE last_modified = NOW();\n    console.log(qb.last_query());\n\n    // 1 (because we updated the last_modified field)\n    console.log(res.affected_rows);\n\n    /*\n     * Resulting Table Structure:\n     *\n     * [\n     *        {name: 'MySQL', version: '5.5.40', last_modified: 1423252221 },\n     *        {name: 'Mongo', version: '2.6.7',  last_modified: 1423252232 },\n     *        {name: 'Postgres', version: '8.4', last_modified: 1423264972 }\n     *    ]\n     */\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"delete\"\u003e\u003c/a\u003e\n\n### .delete(table, where[, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :----------------------------------------------------------------------------------------------------\ntable     | String   | Required  | The table/collection you'd like to delete records from.\nwhere     | Object   | undefined | (optional) Used to avoid having to call `.where()` separately. Pass NULL if you don't want to use it.\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nThis method is used to delete records from a table (SQL) or collection (NoSQL). All identifiers and values are escaped automatically when applicable. The response parameter of the callback should receive a response object with the number of affected rows.\n\n**NOTE:** If tables are added to the querybuilder query cache via the `from()` method, only first table in the array (the first added) will be used for this method.\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Examples**\n\nHere's a contrived example of how it might be used in an app made with the Express framework (NOTE: you should do better with error handling):\n\n```javascript\nconst express = require('express');\nconst app = express();\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\napp.post('/delete_comment/:id', async (req, res) =\u003e {\n    const id = req.params.id;\n    let qb;\n\n    try {\n        qb = await pool.get_connection();\n        const comment = qb.get('comments', {id});\n        const comment_id = comment.id;\n        const results = await qb.delete('comments', {id: comment_id});\n        const num_removed = res.affected_rows;\n        return res.render(`/article/${article_id}`, {num_removed});\n    } catch (err) {\n        console.error(err);\n        return res.status(400).send('Something bad happened.');\n    } finally {\n        if (qb) qb.release();\n    }\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"truncate\"\u003e\u003c/a\u003e\n\n### .truncate(table[, callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :-------------------------------------------\ntable     | String   | Required  | The table/collection you'd like to truncate.\ncallback  | Function | undefined | (optional) What to do when the driver has responded.\n\nFor drivers that support it (MySQL, MSSQL), this method will utilize the `TRUNCATE` directive to empty a table of all it's data. The main difference between the `truncate()` method and the `empty_table()` method is that, when available, and when possible, truncating a table will reset your AUTO_INCREMENT counter back to zero. If you simply delete every row from a table, the next item inserted will just continue with the next highest ID from the deleted records.\n\nFor drivers that don't support the truncate method, this will simply act as a wrapper to the [.empty_table()](#empty_table) method.\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Examples**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\n/*\n * Assume we have a table (with auto-incrementing ID) like this to start with...\n * [\n *   { id: 1, name: 'Mary' },\n *   { id: 2, name: 'Jane' },\n *   { id: 3, name: 'Joe'  }\n * ];\n */\n\nasync function deleteUser() {\n    let qb;\n    try {\n        qb = await pool.get_connection();\n        await qb.truncate('users');\n        await qb.insert('users', { name: 'Bob' });\n        const results = await qb.get_where('users', { id: res.insert_id });\n\n        // { id: 1, name: 'Bob' } (notice ID is 1)\n        console.log('Results: ', results);\n    } catch (err) {\n        console.error(err);\n    } finally {\n        if (qb) qb.release();\n    }\n}\n\ndeleteUser();\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"empty_table\"\u003e\u003c/a\u003e\n\n### .empty_table(table[, callback])\n\nParameter | Type     | Default  | Description\n:-------- | :------- | :------- | :-------------------------------------------\ntable     | String   | Required | The table/collection you'd like to truncate.\ncallback  | Function | Required | What to do when the driver has responded.\n\nThis method will allow you to delete all records from a table/collection.\n\n**Note:** This will *not* reset your `AUTO_INCREMENT`ing primary key field. For that, please use the [.truncate()](#truncate) method where possible.\n\n**Response Type**\n\nObject containing information about the result of the query.\n\n**Examples**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\n/*\n * Assume we have a table like this to start with...\n * [\n *   { id: 1, name: 'Mary' },\n *   { id: 2, name: 'Jane' },\n *   { id: 3, name: 'Joe'  }\n * ];\n */\n\npool.get_connection(qb =\u003e {\n    qb.empty_table('users', (err, res) =\u003e {\n        if (err) throw err;\n        qb.insert('users', {name: 'Bob'}, (err, res) =\u003e {\n            if (err) throw err;\n            qb.get_where('users', {id: res.insert_id}, (err, res) =\u003e {\n                qb.release();\n                if (err) throw err;\n                // { id: 4, name: 'Bob' } (notice ID is 4)\n                console.dir(res);\n            });\n        });\n    });\n});\n```\n\n--------------------------------------------------------------------------------\n\n## Other Library-Specific Methods\nThese are methods that are not part of the query-building chain, but, rather, methods you might call before, after, or during (but not as part of) building a query.\n\nAPI Method                                    | MySQL    | MSSQL    | Oracle   | SQLite   | Postgres | Mongo\n:-------------------------------------------- | :------: | :------: | :------: | :------: | :------: | :------:\n[connection](#connection_settings)            | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[connection_settings()](#connection_settings) | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[disconnect()](#disconnect)                   | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[escape()](#escape)                           | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[get_connection()](#get_connection)           | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[last_query()](#last_query)                   | \u0026#x2713; | \u0026#x2717; |          |          |          |\n[release()](#release)                         | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[get_compiled_select()](#get_compiled_select) | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[get_compiled_insert()](#get_compiled_insert) | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[get_compiled_update()](#get_compiled_update) | \u0026#x2713; | \u0026#x2713; |          |          |          |\n[get_compiled_delete()](#get_compiled_delete) | \u0026#x2713; | \u0026#x2713; |          |          |          |\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"connection\"\u003e\u003c/a\u003e\n\n### .connection()\n\nGet a reference to an instance of the connection handle from the driver that's being utilized under the surface. With that connection handle instance, you can run any of the native methods from that driver that don't have equivalents in this library. For instance, with the `mssql` driver, you would be able to execute stored procedures.\n\n**Example**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mssql', 'pool');\n\npool.get_connection(qb =\u003e {\n    const conn = qb.get_connection();\n    const request = new conn.Request();\n\n    request.input('input_parameter', sql.Int, 8675309);\n    request.output('output_parameter', sql.Int);\n\n    request.execute('call_phone_number', (err, result) =\u003e {\n        qb.release();\n        // Do stuff\n    });\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"connection_settings\"\u003e\u003c/a\u003e\n\n### .connection_settings()\n\nSimply returns your connection settings object (the configuration object used to create your QueryBuilder instance) for reference or use elsewhere. This is not something you'll likely find yourself using but we'll document it nonetheless.\n\n**Example**\n\n```javascript\nconst settings = require('db.json');\nconst qb = new require('node-querybuilder')(settings, 'mssql');\n\n// This results in the same value as the value of the `settings` variable\nconst connection_settings = qb.connection_settings();\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"disconnect\"\u003e\u003c/a\u003e\n\n### .disconnect([callback])\n\nParameter | Type     | Default   | Description\n:-------- | :------- | :-------- | :---------------------------------------------------------\ncallback  | Function | undefined | (optional) What to do when the connection is fully terminated.\n\nDisconnect from the server after your query is complete. You _must_ call this each time after your done querying the database! **NOTE:** You would _not_ use this when using a connection pool. This should only be called when working with single one-off connections (command-line scripts, for example). After disconnecting, all subsequent queries will fail unless you reconnect ([connect()](#connect)).\n\n**Examples**\n\nBelow is a contrived example that gets a list of all users in a users table where their username starts with a `|` (pipe) character. It then loops over each one and removes the `|` from the username and re-inserts it. Notice that the connection is not terminated until all the queries that needed to be executed have been executed.\n\n```javascript\nconst settings = require('db.json');\nconst qb = new require('node-querybuilder')(settings, 'mysql');\n\nqb.like('username','|','right').get_where('users', {active: true}, (err, res) =\u003e {\n    let users = res;\n    (function update_user() {\n        const user = users.shift();\n        user.username = user.username.replace(/\\^|/,'');\n\n        qb.update('users', user, {id: user.id}, (err, res) =\u003e {\n            if (err) {\n                console.error(\"Failed to update user...\", err);\n                qb.diconnect();\n            }\n\n            if (user.length \u003e 0) {\n                setTimeout(update_user, 0);\n            } else {\n                qb.disconnect();\n            }\n        });\n    })();\n});\n\n```\n\nHere's a simpler example so you can better see how it will most often be used:\n\n```javascript\nconst settings = require('db.json');\nconst qb = new require('node-querybuilder')(settings, 'mysql');\n\nqb.get_where('users', {username: 'foobar'}, (err, res) =\u003e {\n    if (err) throw err;\n    qb.disconnect((err) =\u003e { // NOTE: an error here is unlikely\n        if (err) return console.error(err);\n        console.log(\"Success: \", res);\n    });\n});\n```\n\nAs with all functions in this library, it has a Promise-style verion as well. Simply don't supply the callback and a Promise will be returned. Here's an example:\n\n```javascript\nconst settings = require('db.json');\nconst qb = new require('node-querybuilder')(settings, 'mysql');\n\nasync function getFooUsers() {\n    try {\n        const res = await qb.get_where('users', {username: 'foobar'});\n        await qb.disconnect();\n        console.log(\"Success: \", res);\n    } catch (err) {\n        if (err) console.error(err);\n    }\n}\n\ngetFooUsers();\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"escape\"\u003e\u003c/a\u003e\n\n### .escape(value)\n\nParameter | Type  | Default  | Description\n:-------- | :---- | :------- | :------------------------------------------------\nvalue     | Mixed | Required | The value to escape based on your database driver\n\nThis can be used to escape a value using your driver's native escape method. If your driver does not have a native escape method, the value will simply be returned. This is useful for when you want to build a SQL string manually (for instance, you don't want certain items to be escaped).\n\n**What should happen:** _Examples given are for MySQL_\n\nInput Type | Output Type | Ex. Input          | Ex. Output\n:--------- | :---------: | :----------------: | :------------------------:\nString     | String      | \"\\n\\s\\x1a\"         | \"\\\\n\\\\s\\\\x1a\"\nInteger    | String      | 76                 | '76'\nArray      | String      | [1,2,3]            | '1','2',3'\nDate       | String      | new Date()         | '2015-01-30 16:54:23.1856'\nBuffer     | String      | new Buffer(1)      | 'X\\'00\\''\nObject     | String      | {foo: 'bar', i: 3} | \"`foo` = 'bar', `i` = 3\"\n\n**Example**\n\n```javascript\nconst qb = new require('node-querybuilder')(require('db.json'), 'mysql');\nconst sql = 'SELECT count(*) FROM `star_systems` WHERE ' + qb.escape({planet_num: 5}) + ' LIMIT 10';\nqb.query(sql, (err, res) =\u003e {\n    // SELECT count(*) FROM `star_systems` WHERE `planet_num` = 5 LIMIT 10\n    console.log(res);\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_connection\"\u003e\u003c/a\u003e\n\n### .get_connection([callback])\n\nParameter | Type     | Default  | Description\n:-------- | :------- | :------- | :---------------------------------------------------------\ncallback  | Function | Required | What to do when the connection is retrieved (or not) from the pool.\n\nUsed to get a new connection from the connection pool or cluster pool. An instance of the QueryBuilder adapter for your specific connection will be passed to the callback or Promise resolution. Make sure that your connection is [release](#release)d when you are done with it!\n\n**Callback Example**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\npool.get_connection(qb =\u003e {\n    qb.limit(10).get('users', (err, res) =\u003e {\n        qb.release();\n        if (err) return console.error(err);\n        // Do stuff with results\n    });\n});\n```\n\n**Async/Await Example**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\nasync function getUsers() {\n    let qb;\n    try {\n        qb = await pool.get_connection();\n        const res = await qb.limit(10).get('users');\n        // Do stuff with results\n    } catch (err) {\n        console.error(err);\n    } finally {\n        if (qb) qb.release();\n    }\n}\n\ngetUsers();\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"last_query\"\u003e\u003c/a\u003e\n\n### .last_query()\nThis is used to retrieve the query string that was most-recently executed. This MUST be called before closing the connection or releasing a connection back to the pool. This is useful for debugging what the `node-querybuilder` library is executing (or trying to execute).\n\nIf you'd rather the engine not execute the query first, you can always use the appropriate [compilation methods](#compilation_methods) detailed below.\n\n**Examples**\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\npool.get_connection(qb =\u003e {\n    const id = 4531;\n    qb.get('comments', {id}, (err, res) =\u003e {\n        // SELECT * FROM `comments` WHERE `id` = 4531\n        console.log(qb.last_query());\n        qb.release();\n    });\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"release\"\u003e\u003c/a\u003e\n\n### .release()\nReleases a connection back to the pool when you are done with it. Calling this is _super_ important!\n\n**Examples**\n\nBelow is a contrived example (with no error handling--for brevity) that gets a list of all users in a users table where their username starts with a `|` character. It then loops over each one and removes the `|` from the username and re-inserts it. Notice that the connection is not released until all the queries that needed to be executed have been executed.\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\npool.get_connection(qb =\u003e {\n    qb.like('username','|','right').get_where('users', {active: true}, (err, res) =\u003e {\n        let users = res;\n        (function update_user() {\n            const user = users.shift();\n            user.username = user.username.replace(/\\^|/,'');\n\n            qb.update('users', user, {id: user.id}, (err, res) =\u003e {\n                if (user.length \u003e 0) {\n                    setTimeout(update_user, 0);\n                } else {\n                    qb.release();\n                }\n            });\n        })();\n    });\n});\n```\n\nHere's a simpler example so you can better see how it will most often be used\n\n```javascript\nconst settings = require('db.json');\nconst pool = new require('node-querybuilder')(settings, 'mysql', 'pool');\n\npool.get_connection(qb =\u003e {\n    qb.get_where('users', {username: 'foobar'}, (err, res) =\u003e {\n        qb.release();\n        if (err) throw err;\n        console.dir(res);\n    });\n});\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"compilation_methods\"\u003e\u003c/a\u003e\n\n### SQL Compilation Methods\nThese methods can be used to build a query string without having to execute it. This is a fantastic option if you want to use the querybuilder to simply build queries and display the resulting string or to send the compiled query string off to a driver/engine other than the one offered by `node-querybuilder`.\n\nThese are also excellent educational tools and can be used like a SQL/NoSQL language Rosetta Stone of sorts.\n\nThese methods are not asynchronous and, therefore, just return the compiled query string.\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_compiled_select\"\u003e\u003c/a\u003e\n\n#### .get_compiled_select(table)\n**_Alias:_** _compile_select(table)_\n\nParameter | Type   | Default   | Description\n:-------- | :----- | :-------- | :----------------------------------------------------------\ntable     | String | Undefined | (optional) Used to avoid having to call .from() separately.\n\nCompiles a SELECT-like query into a properly-escaped string.\n\n**Example:**\n\nGet certain details of a user account\n\n```javascript\nconst qb = new require('node-querybuilder')(require('db.json'), 'mysql');\n\nconst sql = qb\n    .select(['id','username','first_name','last_name'])\n    .from('users')\n    .like('username','k','after')\n    .get_compiled_select();\n\n// SELECT `id`, `username`, `first_name`, `last_name` FROM `users` WHERE `username` LIKE 'k%'\nconsole.log(sql);\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_compiled_insert\"\u003e\u003c/a\u003e\n\n#### .get_compiled_insert(table)\n**_Alias:_** _compile_insert(table)_\n\nParameter | Type   | Default   | Description\n:-------- | :----- | :-------- | :----------------------------------------------------------\ntable     | String | Undefined | (optional) Used to avoid having to call .from() separately.\n\nCompiles a INSERT-like query into a properly-escaped string.\n\n**Example:**\n\nAdd a new user to a `users` table.\n\n```javascript\nconst qb = new require('node-querybuilder')(require('db.json'), 'mysql');\nconst crypto = require('crypto');\nconst data = {\n    username: 'foobar',\n    password: crypto.createHash('sha1').update('password').digest('hex'),\n    first_name: 'Foo',\n    last_name: 'Bar'\n};\nconst sql = qb.set(data).get_compiled_insert('users');\n\n// INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES ('foobar', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', 'Foo', 'Bar')\nconsole.log(sql);\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_compiled_update\"\u003e\u003c/a\u003e\n\n#### .get_compiled_update(table)\n**_Alias:_** _compile_update(table)_\n\nParameter | Type   | Default   | Description\n:-------- | :----- | :-------- | :----------------------------------------------------------\ntable     | String | Undefined | (optional) Used to avoid having to call .from() separately.\n\nCompiles an UPDATE-like query into a properly-escaped string.\n\n**Example:**\n\nUpdate the password of a user\n\n```javascript\nconst qb = new require('node-querybuilder')(require('db.json'), 'mysql');\nconst crypto = require('crypto');\nconst data = {\n    password: crypto.createHash('sha1').update('P@$$w0rD').digest('hex'),\n};\nconst sql = qb\n    .where('id', 4321)\n    .set(data)\n    .get_compiled_update('users');\n\n// UPDATE `users` SET `password` = '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' WHERE `id` = 4321\nconsole.log(sql);\n```\n\n--------------------------------------------------------------------------------\n\n\u003ca name=\"get_compiled_delete\"\u003e\u003c/a\u003e\n\n#### .get_compiled_delete(table)\n**_Alias:_** _compile_delete(table)_\n\nParameter | Type   | Default   | Description\n:-------- | :----- | :-------- | :----------------------------------------------------------\ntable     | String | Undefined | (optional) Used to avoid having to call .from() separately.\n\nCompiles a SELECT-like query into a properly-escaped string.\n\n**Example:**\n\nDelete a user\n\n```javascript\nconst qb = new require('node-querybuilder')(require('db.json'), 'mysql');\nconst sql = qb.where('id', 4321).get_compiled_delete('users');\n\n// DELETE FROM `users` WHERE `id` = 4321\nconsole.log(sql);\n```\n\n--------------------------------------------------------------------------------\n\n# Contribute\nGot a missing feature you'd like to use? Found a bug? Go ahead and fork this repo, build the feature and issue a pull request.\n\n[npm-version-image]: https://img.shields.io/npm/v/node-querybuilder.svg\n[npm-downloads-image]: https://img.shields.io/npm/dm/node-querybuilder.svg\n[npm-url]: https://npmjs.org/package/node-querybuilder\n[travis-image]: https://img.shields.io/travis/kylefarris/node-querybuilder/master.svg\n[travis-url]: https://travis-ci.org/kylefarris/node-querybuilder\n[node-image]: https://img.shields.io/node/v/node-querybuilder.svg\n[node-url]: https://nodejs.org/en/download\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkylefarris%2Fnode-querybuilder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkylefarris%2Fnode-querybuilder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkylefarris%2Fnode-querybuilder/lists"}