knex, mysql2, pg, sequelize, and sqlite3 are essential tools for managing data in Node.js applications, but they operate at different layers of abstraction. pg and mysql2 are low-level drivers that speak directly to PostgreSQL and MySQL databases, offering maximum control. sqlite3 provides similar low-level access for local file-based databases. knex sits in the middle as a query builder, adding a consistent syntax across different SQL dialects. sequelize is a full Object-Relational Mapper (ORM) that abstracts SQL entirely into JavaScript objects and classes. Choosing the right one depends on how much control you need versus how much convenience you want.
When building server-side JavaScript applications, selecting the right database tool is a critical architectural decision. The packages knex, mysql2, pg, sequelize, and sqlite3 all solve the problem of data persistence, but they approach it from different angles. Some are direct drivers, some are query builders, and one is a full ORM. Understanding these layers helps you avoid over-engineering or painting yourself into a corner. Let's compare how they handle connection, queries, modeling, and maintenance.
Setting up a connection is the first step, and the complexity varies significantly between raw drivers and higher-level tools.
pg requires you to create a pool manager to handle connections efficiently.
// pg: Connection Pool
const { Pool } = require('pg');
const pool = new Pool({
user: 'dbuser',
host: 'localhost',
database: 'mydb',
password: 'secretpassword',
port: 5432,
});
mysql2 also uses a pool but offers a promise wrapper for cleaner async code.
pg but specific to MySQL ports.// mysql2: Promise Pool
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'dbuser',
password: 'secretpassword',
database: 'mydb',
});
sqlite3 connects to a file path instead of a network host.
// sqlite3: File Connection
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./mydb.sqlite');
knex abstracts the connection config behind a client selector.
// knex: Unified Config
const knex = require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: 'dbuser',
password: 'secretpassword',
database: 'mydb',
},
});
sequelize uses a single connection URI or object to initialize the ORM.
// sequelize: ORM Initialization
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('postgres://dbuser:secretpassword@localhost:5432/mydb');
The way you fetch data defines your daily developer experience. Raw drivers give you SQL strings, while ORMs give you methods.
pg executes raw SQL strings with parameterized values.
// pg: Raw Query
const result = await pool.query('SELECT * FROM users WHERE id = $1', [1]);
const rows = result.rows;
mysql2 uses question marks for parameter placeholders instead of dollar signs.
pg but follows MySQL standards.// mysql2: Raw Query
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [1]);
sqlite3 traditionally uses callbacks, though promises can be wrapped.
pg or mysql2.// sqlite3: Callback Query
db.all('SELECT * FROM users WHERE id = ?', [1], (err, rows) => {
if (err) throw err;
console.log(rows);
});
knex chains methods to build queries programmatically.
// knex: Query Builder
const rows = await knex('users').where({ id: 1 }).select('*');
sequelize calls methods on defined models instead of tables.
// sequelize: Model Query
const users = await User.findAll({ where: { id: 1 } });
Defining what your data looks like is where ORMs and drivers diverge the most.
pg has no built-in modeling.
// pg: No Model (Raw SQL Assumption)
// You must ensure table exists via SQL:
// CREATE TABLE users (id INT, name TEXT);
mysql2 also lacks built-in modeling.
// mysql2: No Model (Raw SQL Assumption)
// You must ensure table exists via SQL:
// CREATE TABLE users (id INT, name VARCHAR(255));
sqlite3 requires manual schema management.
CREATE TABLE commands on initialization.// sqlite3: Manual Schema
db.run(`CREATE TABLE IF NOT EXISTS users (id INT, name TEXT)`);
knex provides schema building tools but not data models.
// knex: Schema Builder
await knex.schema.createTable('users', (table) => {
table.increments('id');
table.string('name');
});
sequelize defines models as JavaScript classes.
// sequelize: Model Definition
const User = sequelize.define('User', {
name: { type: DataTypes.STRING },
});
Changing your database structure over time requires a migration strategy.
pg does not include a migration system.
node-pg-migrate.// pg: External Tool Required
// Requires separate package installation and CLI setup
mysql2 lacks built-in migrations.
db-migrate alongside it.// mysql2: External Tool Required
// Requires separate package installation and CLI setup
sqlite3 has no migration tooling included.
// sqlite3: Custom Scripts
// Manual execution of ALTER TABLE commands in code
knex includes a robust migration CLI out of the box.
// knex: Built-in Migration
// knex migrate:make create_users_table
// Creates a file with export.up and export.down functions
sequelize provides a CLI for model-based migrations.
// sequelize: CLI Migration
// npx sequelize-cli migration:generate --name create-users
// Generates a file with queryInterface.createTable
| Feature | pg / mysql2 | sqlite3 | knex | sequelize |
|---|---|---|---|---|
| Type | Database Driver | Database Driver | Query Builder | ORM |
| Query Style | Raw SQL Strings | Raw SQL Strings | Method Chaining | Model Methods |
| Modeling | None (SQL Only) | None (SQL Only) | Schema Builder | JavaScript Classes |
| Migrations | External Tools Needed | Manual Scripts | Built-in CLI | Built-in CLI |
| Learning Curve | Low (Just SQL) | Low (Just SQL) | Medium | High |
| Best For | Full Control | Local / Testing | Flexibility | Rapid Development |
pg and mysql2 are the foundation layers โ choose them if you want zero abstraction and maximum performance. They are perfect when your team knows SQL well and wants to avoid the magic of an ORM. sqlite3 serves a niche role โ use it for local testing or small tools, but avoid it for high-traffic web servers due to locking constraints.
knex is the sweet spot for many teams โ it gives you structure without hiding the SQL. It is ideal when you want migrations and a query builder but still need to write complex joins or raw queries occasionally. sequelize is the productivity engine โ pick it when you want to model data as objects and let the library handle the relationships. It speeds up initial development but can become complex to debug when things go wrong.
Final Thought: If you are building a simple API, start with knex for balance. If you are building a complex enterprise system with strict data rules, sequelize might save you time. If you need raw speed and specific database features, stick with pg or mysql2.
Choose sqlite3 if you need a lightweight, file-based database for local development, testing, or small single-user applications. It is perfect for prototypes or edge cases where setting up a full database server is impractical. Avoid this for high-concurrency production web apps due to file-locking limitations and native binding requirements.
Choose knex if you want a balance between raw SQL control and developer convenience. It is ideal when you need to support multiple database types without rewriting queries, or when you want a robust migration system without the overhead of a full ORM. It works well for teams that prefer writing SQL-like logic but want it wrapped in JavaScript functions.
Choose mysql2 if your project relies exclusively on MySQL and you need high performance with minimal abstraction. It is suitable for developers who want to write raw SQL queries directly and manage connections manually. This package is a strong fit for microservices where each service owns its specific database schema.
Choose pg if you are building on PostgreSQL and want the standard, battle-tested client library. It is best for teams that value stability and direct access to Postgres-specific features like JSONB or full-text search. Use this when you do not need an ORM and prefer managing data structures through raw SQL or external schema tools.
Choose sequelize if you prefer defining data models as JavaScript classes and want the library to handle SQL generation for you. It is ideal for complex applications where relationships between data tables are intricate and need strict enforcement. This tool saves time on boilerplate but requires learning its specific API and lifecycle hooks.
Note: This repository is currently unmaintained. We will not update any of its issues or pull requests.
Asynchronous, non-blocking SQLite3 bindings for Node.js.
You can use npm or yarn toย install sqlite3:
npm install sqlite3
# or
yarn add sqlite3
master branch: npm install https://github.com/tryghost/node-sqlite3/tarball/mastersqlite3 v5+ was rewritten to use Node-API so prebuilt binaries do not need to be built for specific Node versions. sqlite3 currently builds for both Node-API v3 and v6. Check the Node-API version matrix to ensure your Node version supports one of these. The prebuilt binaries should be supported on Node v20.17.0+.
The module uses prebuild-install to download the prebuilt binary for your platform, if it exists. These binaries are hosted on GitHub Releases for sqlite3 versions above 5.0.2, and they are hosted on S3 otherwise. The following targets are currently provided:
darwin-arm64darwin-x64linux-arm64linux-x64linuxmusl-arm64linuxmusl-x64win32-x64Unfortunately, prebuild cannot differentiate between armv6 and armv7, and instead uses arm as the {arch}. Until that is fixed, you will still need to install sqlite3 from source.
Support for other platforms and architectures may be added in the future if CI supports building on them.
If your environment isn't supported, it'll use node-gyp to build SQLite, but you will need to install a C++ compiler and linker.
It is also possible to make your own build of sqlite3 fromย itsย source insteadย of itsย npmย package (Seeย below.).
The sqlite3 module also works with node-webkit ifย node-webkit contains aย supported version ofย Node.js engine. (Seeย below.)
SQLite's SQLCipher extension isย also supported. (Seeย below.)
See the API documentation in the wiki.
Note: theย module mustย be installed beforeย use.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run("CREATE TABLE lorem (info TEXT)");
const stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (let i = 0; i < 10; i++) {
stmt.run("Ipsum " + i);
}
stmt.finalize();
db.each("SELECT rowid AS id, info FROM lorem", (err, row) => {
console.log(row.id + ": " + row.info);
});
});
db.close();
To skip searching for pre-compiled binaries, and force a build from source, use
npm install --build-from-source
The sqlite3 module depends only on libsqlite3. However, by default, an internal/bundled copy of sqlite will be built and statically linked, so an externally installed sqlite3 is not required.
If you wish to install against an external sqlite then you need to pass the --sqlite argument to npm wrapper:
npm install --build-from-source --sqlite=/usr/local
If building against an external sqlite3 make sure to have the development headers available. Mac OS X ships with these by default. If you don't have them installed, install the -dev package with your package manager, e.g. apt-get install libsqlite3-dev for Debian/Ubuntu. Make sure that you have at least libsqlite3 >= 3.6.
Note, if building against homebrew-installed sqlite on OS X you can do:
npm install --build-from-source --sqlite=/usr/local/opt/sqlite/
The default sqlite file header is "SQLite format 3". You can specify a different magic, though this will make standard tools and libraries unable to work with your files.
npm install --build-from-source --sqlite_magic="MyCustomMagic15"
Note that the magic must be exactly 15 characters long (16 bytes including null terminator).
Because of ABI differences, sqlite3 must be built in a custom to beย used withย node-webkit.
To build sqlite3 for node-webkit:
Install nw-gyp globally: npm install nw-gyp -g (unless already installed)
Build theย module with the custom flags of --runtime, --target_arch, and --target:
NODE_WEBKIT_VERSION="0.8.6" # see latest version at https://github.com/rogerwang/node-webkit#downloads
npm install sqlite3 --build-from-source --runtime=node-webkit --target_arch=ia32 --target=$(NODE_WEBKIT_VERSION)
You can also run this command from within a sqlite3 checkout:
npm install --build-from-source --runtime=node-webkit --target_arch=ia32 --target=$(NODE_WEBKIT_VERSION)
Remember the following:
You must provide the right --target_arch flag. ia32 is needed to target 32bit node-webkit builds, while x64 will target 64bit node-webkit builds (if available for your platform).
After the sqlite3 package is built for node-webkit itย cannot run inย theย vanilla Node.js (and viceย versa).
npm test of theย node-webkit's package wouldย fail.Visit the โUsing Node modulesโ article inย the node-webkit's wiki forย moreย details.
For instructions on building SQLCipher, see Building SQLCipher for Node.js. Alternatively, you can install it with your local package manager.
To run against SQLCipher, you need to compile sqlite3 from source by passing build options like:
npm install sqlite3 --build-from-source --sqlite_libname=sqlcipher --sqlite=/usr/
node -e 'require("sqlite3")'
If your SQLCipher is installed in a custom location (if you compiled and installed it yourself), you'll need to set some environment variables:
Set the location where brew installed it:
export LDFLAGS="-L`brew --prefix`/opt/sqlcipher/lib"
export CPPFLAGS="-I`brew --prefix`/opt/sqlcipher/include/sqlcipher"
npm install sqlite3 --build-from-source --sqlite_libname=sqlcipher --sqlite=`brew --prefix`
node -e 'require("sqlite3")'
Set the location where make installed it:
export LDFLAGS="-L/usr/local/lib"
export CPPFLAGS="-I/usr/local/include -I/usr/local/include/sqlcipher"
export CXXFLAGS="$CPPFLAGS"
npm install sqlite3 --build-from-source --sqlite_libname=sqlcipher --sqlite=/usr/local --verbose
node -e 'require("sqlite3")'
Running sqlite3 through electron-rebuild does not preserve the SQLCipher extension, so some additional flags are needed to make this build Electron compatible. Your npm install sqlite3 --build-from-source command needs these additional flags (be sure to replace the target version with the current Electron version you are working with):
--runtime=electron --target=18.2.1 --dist-url=https://electronjs.org/headers
In the case of MacOS with Homebrew, the command should look like the following:
npm install sqlite3 --build-from-source --sqlite_libname=sqlcipher --sqlite=`brew --prefix` --runtime=electron --target=18.2.1 --dist-url=https://electronjs.org/headers
npm test
Thanks to Orlando Vazquez, Eric Fredricksen and Ryan Dahl for their SQLite bindings for node, and to mraleph on Freenode's #v8 for answering questions.
This module was originally created by Mapbox & is now maintained by Ghost.
We use GitHub releases for notes on the latest versions. See CHANGELOG.md in git history for details on older versions.
Copyright (c) 2013-2026 Mapbox & Ghost Foundation
node-sqlite3 is BSD licensed.