sqlite3 vs knex vs mysql2 vs pg vs sequelize
Selecting Database Tools for Node.js Backends
sqlite3knexmysql2pgsequelizeSimilar Packages:

Selecting Database Tools for Node.js Backends

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
sqlite32,448,6376,4113.4 MB1747 months agoBSD-3-Clause
knex020,337941 kB7553 months agoMIT
mysql204,388630 kB45710 days agoMIT
pg013,218103 kB5489 days agoMIT
sequelize030,3502.91 MB1,1097 months agoMIT

Choosing Database Tools for Node.js Backends

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.

๐Ÿ”Œ Connecting to the Database

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.

  • You must configure host, user, and database name explicitly.
  • The pool handles opening and closing connections for you.
// 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.

  • Configuration is similar to pg but specific to MySQL ports.
  • You access the promise interface to avoid callback hell.
// 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.

  • It does not use a pool by default in the basic package.
  • Connections are often single-threaded and file-locked.
// sqlite3: File Connection
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./mydb.sqlite');

knex abstracts the connection config behind a client selector.

  • You specify the client type (e.g., 'pg', 'mysql', 'sqlite3').
  • It creates the pool internally based on your configuration.
// 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.

  • It sets up pooling and authentication automatically.
  • You define the dialect to match your database engine.
// sequelize: ORM Initialization
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('postgres://dbuser:secretpassword@localhost:5432/mydb');

๐Ÿ“ Running Queries

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.

  • You write standard SQL syntax directly in your code.
  • This gives you full access to Postgres-specific features.
// 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.

  • The syntax is nearly identical to pg but follows MySQL standards.
  • You still manage the SQL string structure manually.
// mysql2: Raw Query
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [1]);

sqlite3 traditionally uses callbacks, though promises can be wrapped.

  • The API is older and less modern than pg or mysql2.
  • You must handle errors in the callback function.
// 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.

  • You do not write SQL strings directly for basic operations.
  • The library translates chains into safe SQL for your dialect.
// knex: Query Builder
const rows = await knex('users').where({ id: 1 }).select('*');

sequelize calls methods on defined models instead of tables.

  • You interact with JavaScript classes, not database tables.
  • The library generates the SQL behind the scenes.
// sequelize: Model Query
const users = await User.findAll({ where: { id: 1 } });

๐Ÿ—‚๏ธ Data Modeling

Defining what your data looks like is where ORMs and drivers diverge the most.

pg has no built-in modeling.

  • You define schemas in SQL migration files.
  • Your code assumes the structure exists in the database.
// 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.

  • Structure is managed entirely via database scripts.
  • Code relies on documentation to know column names.
// 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.

  • You run CREATE TABLE commands on initialization.
  • There is no enforcement of types in the JavaScript layer.
// sqlite3: Manual Schema
db.run(`CREATE TABLE IF NOT EXISTS users (id INT, name TEXT)`);

knex provides schema building tools but not data models.

  • You can define table structure in JavaScript migration files.
  • It does not create JavaScript classes for rows.
// knex: Schema Builder
await knex.schema.createTable('users', (table) => {
  table.increments('id');
  table.string('name');
});

sequelize defines models as JavaScript classes.

  • You specify types and validation rules in code.
  • The library can sync these models to the database automatically.
// sequelize: Model Definition
const User = sequelize.define('User', {
  name: { type: DataTypes.STRING },
});

๐Ÿ”„ Migrations

Changing your database structure over time requires a migration strategy.

pg does not include a migration system.

  • You must use external tools like node-pg-migrate.
  • This adds complexity to your build pipeline.
// pg: External Tool Required
// Requires separate package installation and CLI setup

mysql2 lacks built-in migrations.

  • You need to script your own SQL file execution.
  • Common to use tools like db-migrate alongside it.
// mysql2: External Tool Required
// Requires separate package installation and CLI setup

sqlite3 has no migration tooling included.

  • Developers often write custom scripts to alter tables.
  • This can lead to inconsistent states across environments.
// sqlite3: Custom Scripts
// Manual execution of ALTER TABLE commands in code

knex includes a robust migration CLI out of the box.

  • You create files for up and down changes.
  • It tracks which migrations have run in a special table.
// 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.

  • It generates migration files based on your model changes.
  • This keeps your code and database schema in sync.
// sequelize: CLI Migration
// npx sequelize-cli migration:generate --name create-users
// Generates a file with queryInterface.createTable

๐Ÿ“Š Summary Table

Featurepg / mysql2sqlite3knexsequelize
TypeDatabase DriverDatabase DriverQuery BuilderORM
Query StyleRaw SQL StringsRaw SQL StringsMethod ChainingModel Methods
ModelingNone (SQL Only)None (SQL Only)Schema BuilderJavaScript Classes
MigrationsExternal Tools NeededManual ScriptsBuilt-in CLIBuilt-in CLI
Learning CurveLow (Just SQL)Low (Just SQL)MediumHigh
Best ForFull ControlLocal / TestingFlexibilityRapid Development

๐Ÿ’ก Final Recommendation

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.

How to Choose: sqlite3 vs knex vs mysql2 vs pg vs sequelize

  • sqlite3:

    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.

  • knex:

    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.

  • mysql2:

    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.

  • pg:

    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.

  • sequelize:

    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.

README for sqlite3

:no_entry: [DEPRECATED] node-sqlite3

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.

Latest release Build Status FOSSA Status N-API v3 Badge N-API v6 Badge

Features

Installing

You can use npm or yarn toย install sqlite3:

  • (recommended) Latest published package:
npm install sqlite3
# or
yarn add sqlite3
  • GitHub's master branch: npm install https://github.com/tryghost/node-sqlite3/tarball/master

Prebuilt binaries

sqlite3 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-arm64
  • darwin-x64
  • linux-arm64
  • linux-x64
  • linuxmusl-arm64
  • linuxmusl-x64
  • win32-x64

Unfortunately, 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.

Other ways to install

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.)

API

See the API documentation in the wiki.

Usage

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();

Source install

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/

Custom file header (magic)

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).

Building for node-webkit

Because of ABI differences, sqlite3 must be built in a custom to beย used withย node-webkit.

To build sqlite3 for node-webkit:

  1. Install nw-gyp globally: npm install nw-gyp -g (unless already installed)

  2. 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).

    • Forย example, 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.

Building for SQLCipher

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:

On OS X with Homebrew

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")'

On most Linuxes (including Raspberry Pi)

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")'

Custom builds and Electron

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

Testing

npm test

Contributors

Acknowledgments

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.

Changelog

We use GitHub releases for notes on the latest versions. See CHANGELOG.md in git history for details on older versions.

Copyright & license

Copyright (c) 2013-2026 Mapbox & Ghost Foundation

node-sqlite3 is BSD licensed.

FOSSA Status