better-sqlite3 vs sqlite3 vs sqlite
SQLite Database Libraries for Node.js
better-sqlite3sqlite3sqliteSimilar Packages:
SQLite Database Libraries for Node.js

SQLite Database Libraries for Node.js are packages that allow Node.js applications to interact with SQLite databases. These libraries provide APIs to perform CRUD (Create, Read, Update, Delete) operations, execute SQL queries, and manage database connections. They are essential for applications that require lightweight, file-based databases, such as web apps, desktop apps, and IoT devices. Popular SQLite libraries for Node.js include sqlite3, better-sqlite3, and sqlite, each offering unique features and performance characteristics.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
better-sqlite32,301,8176,68810.2 MB948 days agoMIT
sqlite31,990,6546,4203.35 MB1722 years agoBSD-3-Clause
sqlite225,45992898.5 kB72 years agoMIT
Feature Comparison: better-sqlite3 vs sqlite3 vs sqlite

Performance

  • better-sqlite3:

    better-sqlite3 is known for its high performance, especially for synchronous operations. It is faster than sqlite3 for most use cases due to its efficient handling of queries and minimal overhead.

  • sqlite3:

    sqlite3 provides reliable performance for asynchronous database operations. While it may not be as fast as better-sqlite3 for all tasks, it is efficient for handling large datasets and streaming data.

  • sqlite:

    sqlite offers good performance, particularly for asynchronous operations. However, its promise-based nature may introduce some overhead compared to synchronous libraries, especially for small, quick queries.

API Design

  • better-sqlite3:

    better-sqlite3 features a simple and intuitive API with synchronous methods for executing queries, managing transactions, and handling results. Its design prioritizes ease of use and clarity, making it accessible for developers of all skill levels.

  • sqlite3:

    sqlite3 offers a traditional callback-based API for asynchronous database operations. It also supports streaming data, which can be beneficial for handling large result sets. The API is straightforward but may require more boilerplate code compared to promise-based libraries.

  • sqlite:

    sqlite provides a modern, promise-based API that allows for more flexible and asynchronous database interactions. Its design is well-suited for modern JavaScript applications, particularly those using async/await syntax.

Synchronous vs Asynchronous

  • better-sqlite3:

    better-sqlite3 is primarily a synchronous library, which means that database operations are performed in a blocking manner. This can lead to simpler code and better performance for many use cases, but it may not be suitable for applications that require non-blocking I/O.

  • sqlite3:

    sqlite3 supports asynchronous operations using callbacks, making it suitable for applications that need to perform multiple database tasks without freezing the main thread. It also allows for streaming data, which can help reduce memory usage when working with large datasets.

  • sqlite:

    sqlite is fully asynchronous and uses promises for all database operations. This makes it a great choice for modern applications that need to handle multiple tasks concurrently without blocking the event loop.

Streaming Support

  • better-sqlite3:

    better-sqlite3 does not natively support streaming data, as it focuses on synchronous operations. However, you can iterate over query results using a simple loop, which works well for most use cases.

  • sqlite3:

    sqlite3 has excellent streaming support, allowing you to process large result sets without loading all data into memory at once. This is particularly useful for applications that work with big data or need to minimize memory usage.

  • sqlite:

    sqlite does not provide built-in streaming support, but its promise-based API allows for efficient handling of large datasets by processing results in batches or using async iterators.

Ease of Use: Code Examples

  • better-sqlite3:

    Simple CRUD Operations with better-sqlite3

    const Database = require('better-sqlite3');
    const db = new Database('my-database.db');
    
    // Create a table
    db.exec(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)`);
    
    // Insert a user
    const insert = db.prepare(`INSERT INTO users (name) VALUES (?)`);
    insert.run('Alice');
    
    // Query users
    const users = db.prepare(`SELECT * FROM users`).all();
    console.log(users);
    
    // Close the database
    db.close();
    
  • sqlite3:

    Simple CRUD Operations with sqlite3

    const sqlite3 = require('sqlite3').verbose();
    const db = new sqlite3.Database('my-database.db');
    
    // Create a table
    db.serialize(() => {
      db.run(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)`);
    
      // Insert a user
    db.run(`INSERT INTO users (name) VALUES (?)`, 'Alice');
    
      // Query users
    db.all(`SELECT * FROM users`, (err, rows) => {
        if (err) throw err;
        console.log(rows);
      });
    });
    
    // Close the database
    db.close();
    
  • sqlite:

    Simple CRUD Operations with sqlite

    import { Database } from 'sqlite';
    import sqlite3 from 'sqlite3';
    
    const db = await Database.open({
      filename: 'my-database.db',
      driver: sqlite3.Database
    });
    
    // Create a table
    await db.exec(`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)`);
    
    // Insert a user
    await db.run(`INSERT INTO users (name) VALUES (?)`, 'Alice');
    
    // Query users
    const users = await db.all(`SELECT * FROM users`);
    console.log(users);
    
    // Close the database
    await db.close();
    
How to Choose: better-sqlite3 vs sqlite3 vs sqlite
  • better-sqlite3:

    Choose better-sqlite3 if you need a fast, simple, and efficient SQLite library with synchronous APIs and excellent performance for most use cases. It is ideal for applications where ease of use and speed are priorities.

  • sqlite3:

    Choose sqlite3 if you need a well-established, widely-used library with support for asynchronous operations and streaming. It is a good choice for applications that require a robust and reliable solution with a large community and extensive documentation.

  • sqlite:

    Choose sqlite if you prefer a modern, promise-based API with support for both SQLite and WebSQL. This library is suitable for projects that require a more flexible and asynchronous approach to database interactions.

README for better-sqlite3

better-sqlite3 Build Status

The fastest and simplest library for SQLite in Node.js.

  • Full transaction support
  • High performance, efficiency, and safety
  • Easy-to-use synchronous API (better concurrency than an asynchronous API... yes, you read that correctly)
  • Support for user-defined functions, aggregates, virtual tables, and extensions
  • 64-bit integers (invisible until you need them)
  • Worker thread support (for large/slow queries)

Help this project stay strong! 💪

better-sqlite3 is used by thousands of developers and engineers on a daily basis. Long nights and weekends were spent keeping this project strong and dependable, with no ask for compensation or funding, until now. If your company uses better-sqlite3, ask your manager to consider supporting the project:

How other libraries compare

select 1 row  get() select 100 rows   all()  select 100 rows iterate() 1-by-1insert 1 row run()insert 100 rows in a transaction
better-sqlite31x1x1x1x1x
sqlite and sqlite311.7x slower2.9x slower24.4x slower2.8x slower15.6x slower

You can verify these results by running the benchmark yourself.

Installation

npm install better-sqlite3

Requires Node.js v14.21.1 or later. Prebuilt binaries are available for LTS versions. If you have trouble installing, check the troubleshooting guide.

Usage

const db = require('better-sqlite3')('foobar.db', options);

const row = db.prepare('SELECT * FROM users WHERE id = ?').get(userId);
console.log(row.firstName, row.lastName, row.email);

Though not required, it is generally important to set the WAL pragma for performance reasons.

db.pragma('journal_mode = WAL');
In ES6 module notation:
import Database from 'better-sqlite3';
const db = new Database('foobar.db', options);
db.pragma('journal_mode = WAL');

Why should I use this instead of node-sqlite3?

  • node-sqlite3 uses asynchronous APIs for tasks that are either CPU-bound or serialized. That's not only bad design, but it wastes tons of resources. It also causes mutex thrashing which has devastating effects on performance.
  • node-sqlite3 exposes low-level (C language) memory management functions. better-sqlite3 does it the JavaScript way, allowing the garbage collector to worry about memory management.
  • better-sqlite3 is simpler to use, and it provides nice utilities for some operations that are very difficult or impossible in node-sqlite3.
  • better-sqlite3 is much faster than node-sqlite3 in most cases, and just as fast in all other cases.

When is this library not appropriate?

In most cases, if you're attempting something that cannot be reasonably accomplished with better-sqlite3, it probably cannot be reasonably accomplished with SQLite in general. For example, if you're executing queries that take one second to complete, and you expect to have many concurrent users executing those queries, no amount of asynchronicity will save you from SQLite's serialized nature. Fortunately, SQLite is very very fast. With proper indexing, we've been able to achieve upward of 2000 queries per second with 5-way-joins in a 60 GB database, where each query was handling 5–50 kilobytes of real data.

If you have a performance problem, the most likely causes are inefficient queries, improper indexing, or a lack of WAL mode—not better-sqlite3 itself. However, there are some cases where better-sqlite3 could be inappropriate:

  • If you expect a high volume of concurrent reads each returning many megabytes of data (i.e., videos)
  • If you expect a high volume of concurrent writes (i.e., a social media site)
  • If your database's size is near the terabyte range

For these situations, you should probably use a full-fledged RDBMS such as PostgreSQL.

Upgrading

Upgrading your better-sqlite3 dependency can potentially introduce breaking changes, either in the better-sqlite3 API (if you upgrade to a new major version), or between your existing database(s) and the underlying version of SQLite. Before upgrading, review:

Documentation

License

MIT