SQLite library with support for opening and writing databases, prepared statements, and more. This SQLite library is in pure javascript (compiled with emscripten).
sql.js is a javascript SQL database. It allows you to create a relational database and query it entirely in the browser. You can try it in this online demo. It uses a virtual database file stored in memory, and thus doesn't persist the changes made to the database. However, it allows you to import any existing sqlite file, and to export the created database as a JavaScript typed array.
sql.js can be used like any traditional JavaScript library. If you are building a native application in JavaScript (using Electron for instance), or are working in node.js, you will likely prefer to use a native binding of SQLite to JavaScript. A native binding will not only be faster because it will run native code, but it will also be able to work on database files directly instead of having to load the entire database in memory, avoiding out of memory errors and further improving performances.
SQLite is public domain, sql.js is MIT licensed.
API documentation
A full API documentation for all the available classes and methods is available.
It is generated from comments inside the source code, and is thus always up to date.
Usage
For a single-file setup, use sql-wasm-inline.js. It embeds the WebAssembly binary in the JavaScript file, so there is no separate .wasm asset to serve and no locateFile configuration:
const initSqlJs = require('sql.js/dist/sql-wasm-inline.js');const SQL = await initSqlJs();const db = new SQL.Database();
In a browser, load <script src="/dist/sql-wasm-inline.js"></script> and call initSqlJs() in the same way. This build requires WebAssembly support and uses the same asynchronous API as the default build. Embedding the binary makes the JavaScript file larger; the default build keeps it separate for independent caching and streaming compilation.
By default, sql.js uses wasm, and thus needs to load a .wasm file in addition to the javascript library. You can find this file in ./node_modules/sql.js/dist/sql-wasm.wasm after installing sql.js from npm, and instruct your bundler to add it to your static assets or load it from a CDN. Then use the locateFile property of the configuration object passed to initSqlJs to indicate where the file is. If you use an asset builder such as webpack, you can automate this. See this demo of how to integrate sql.js with webpack (and react).
const initSqlJs = require('sql.js');// or if you are in a browser:// const initSqlJs = window.initSqlJs;const SQL = await initSqlJs({ // Required to load the wasm binary asynchronously. Of course, you can host it wherever you want // You can omit locateFile completely when running in node locateFile: file => `https://sql.js.org/dist/${file}`});// Create a databaseconst db = new SQL.Database();// NOTE: You can also use new SQL.Database(data) where// data is an Uint8Array representing an SQLite database file// Execute a single SQL string that contains multiple statementslet sqlstr = "CREATE TABLE hello (a int, b char); \INSERT INTO hello VALUES (0, 'hello'); \
The test files provide up to date example of the use of the api.
Inside the browser
Example HTML file:
<meta charset="utf8" /><html> <script src='/dist/sql-wasm.js'></script> <script> config = { locateFile: filename => `/dist/${filename}` } // The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser. // We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder. initSqlJs(config).then(function(SQL){ //Create the database const db = new SQL.Database(); // Run a query without reading the results db.run(
Creating a database from a file chosen by the user
SQL.Database constructor takes an array of integer representing a database file as an optional parameter.
The following code uses an HTML input as the source for loading a database:
dbFileElm.onchange = () => { const f = dbFileElm.files[0]; const r = new FileReader(); r.onload = function() { const Uints = new Uint8Array(r.result); db = new SQL.Database(Uints); } r.readAsArrayBuffer(f);}
const xhr = new XMLHttpRequest();// For example: https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlitexhr.open('GET', '/path/to/database.sqlite', true);xhr.responseType = 'arraybuffer';xhr.onload = e => { const uInt8Array = new Uint8Array(xhr.response); const db = new SQL.Database(uInt8Array); const contents = db.exec("SELECT * FROM my_table"); // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]};xhr.send();
The Emscripten 6 builds require Node.js 18.3 or newer when run in Node.js.
Contributor tooling and CI use Node.js 24 LTS.
sql.js is hosted on npm. To install it, you can simply run npm install sql.js.
Alternatively, you can simply download sql-wasm.js and sql-wasm.wasm, from the download link below.
read a database from the disk:
const fs = require('fs');const initSqlJs = require('sql.js');const filebuffer = fs.readFileSync('test.sqlite');initSqlJs().then(function(SQL){ // Load the db const db = new SQL.Database(filebuffer);});
write a database to the disk
You need to convert the result of db.export to a buffer
const fs = require("fs");// [...] (create the database)const data = db.export();const buffer = Buffer.from(data);fs.writeFileSync("filename.sqlite", buffer);
If you don't want to run CPU-intensive SQL queries in your main application thread,
you can use the more limited WebWorker API.
You will need to download worker.sql-wasm.js and sql-wasm.wasm from the release page.
For a single-file worker, use worker.sql-wasm-inline.js; it includes the WebAssembly binary and needs no companion file.
Example:
<script> const worker = new Worker("/dist/worker.sql-wasm.js"); worker.onmessage = () => { console.log("Database opened"); worker.onmessage = event => { console.log(event.data); // The result of the query }; worker.postMessage({ id: 2, action: "exec", sql: "SELECT age,name FROM test WHERE id=$id", params: { "$id": 1 } }); }; worker.
Enabling BigInt support
If you need BigInt support, it is partially supported since most browsers now supports it including Safari.Binding BigInt is still not supported, only getting BigInt from the database is supported for now.
<script> const stmt = db.prepare("SELECT * FROM test"); const config = {useBigInt: true}; /*Pass optional config param to the get function*/ while (stmt.step()) console.log(stmt.get(null, config)); /*OR*/ const results = db.exec("SELECT * FROM test", config); console.log(results[0].values)</script>
On WebWorker, you can just add config param before posting a message. With this, you wont have to pass config param on get function.
Choose between the default WebAssembly build, which loads a separate binary, and the inline build, which embeds it in one JavaScript file.
Upgrading from 0.x to 1.x
Version 1.0 and later load asynchronously, whereas version 0.x loaded synchronously.
So in the past, you would:
<script src='js/sql.js'></script><script> const db = new SQL.Database(); //...</script>
or:
const SQL = require('sql.js');const db = new SQL.Database();//...
Version 1.x:
<script src='dist/sql-wasm.js'></script><script> initSqlJs({ locateFile: filename => `/dist/${filename}` }).then(function(SQL){ const db = new SQL.Database(); //... });</script>
or:
const initSqlJs = require('sql.js');initSqlJs().then(function(SQL){ const db = new SQL.Database(); //...});
NOTHING is now a reserved word in SQLite, whereas previously it was not. This could cause errors like Error: near "nothing": syntax error
Downloading and using builds
The release page provides sql-wasm-inline.js and worker.sql-wasm-inline.js as standalone downloads. The sqljs-wasm.zip archive contains the default JavaScript loader and WebAssembly binary; sqljs-worker-wasm.zip contains the worker loader and its binary.
The sqljs-all.zip archive and npm package include the following WebAssembly builds:
Build
Companion file
Use
sql-wasm.js
sql-wasm.wasm
Default production build for browsers and Node.js.
sql-wasm-debug.js
sql-wasm-debug.wasm
Development build with assertions.
sql-wasm-browser.js
sql-wasm-browser.wasm
Browser-only production build, selected by the npm browser export.
sql-wasm-browser-debug.js
sql-wasm-browser-debug.wasm
Browser-only development build.
sql-wasm-inline.js
None
Production build with the WebAssembly binary embedded.