Website Vidya
Cloud & DevOpsStep-by-Step Guide

sqlite3 Command Line in Linux: Create, Query & Export Databases

Learn sqlite3 command line with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
12 min read
PDF Cheat Sheet
sqlite3 Command Line in Linux: Create, Query & Export Databases
AI Executive SummaryWebsiteVidya AI

12 min read

Learn sqlite3 command line with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What sqlite3 Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

SQLite is the most widely deployed relational database engine in the world, powering local state storage for Linux system utilities (including dnf/rpm, NetworkManager, Fail2ban, and Firefox), edge microservices, and embedded applications. Mastering the sqlite3 command line interface allows developers and Linux system administrators to inspect schema definitions, run ad-hoc analytical queries, import and export CSV/JSON datasets, and perform online hot backups directly from an SSH session.

Unlike client-server RDBMS platforms such as PostgreSQL or MySQL, SQLite does not run a background daemon listening on a TCP port. Instead, the sqlite3 binary links the complete transactional SQLite C engine directly into its process space and operates directly on a single ordinary disk file (plus optional rollback journal or Write-Ahead Log files in the same directory).

In this guide, we examine how sqlite3 handles file locking and WAL concurrency on Linux filesystems, clarify the critical difference between standard SQL statements and CLI dot-commands, review formatting and safety flags, and demonstrate practical examples and shell automation workflows.

Advertisement
sqlite3 Command Line in Linux: Create, Query & Export Databases — syntax, flags, and practical terminal workflow diagram
sqlite3 Command Line in Linux: Create, Query & Export Databases — command syntax, key options, and production workflow reference.

What sqlite3 Does and When to Use It

Because SQLite is a serverless embedded library (libsqlite3), running sqlite3 mydata.db opens a direct POSIX file descriptor to mydata.db and uses fcntl(2) byte-range advisory locks to coordinate concurrent readers and writers across processes. Notice that sqlite3 creates the database file lazily: running sqlite3 new.db opens the shell in memory, and the file is only materialized on disk once you execute a DDL/DML statement (such as CREATE TABLE) or run .save.

In modern production Linux deployments, enabling Write-Ahead Logging via PRAGMA journal_mode=WAL; creates two companion files alongside the main database: filename-wal (which appends committed transactions sequentially) and filename-shm (an mmap-backed shared-memory index). Under WAL mode, readers never block writers and writers never block readers, making it safe to run read-only diagnostic queries from the sqlite3 CLI against a live application database without stalling production web requests.

Designed around the Unix philosophy of composable text streams, sqlite3 reads byte or line streams from standard input (stdin) or file paths, applies deterministic transformations in memory, and writes results to standard output (stdout) while routing diagnostic messages to standard error (stderr).

Availability and Installation Across Linux Distributions

The sqlite3 utility is packaged in sqlite3 across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether sqlite3 is installed and inspect which binary path and version your shell resolves:

type -a sqlite3
sqlite3 --version 2>/dev/null || man -f sqlite3

# Illustrative output (reviewed against documentation)
sqlite3 is /usr/bin/sqlite3
sqlite3 (sqlite3)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y sqlite3

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y sqlite

# Arch Linux
sudo pacman -S --noconfirm sqlite

# Alpine Linux
sudo apk add --no-cache sqlite

Command Syntax, Arguments, and Exit Status Codes

sqlite3 [OPTIONS] [FILENAME [SQL...]]

The sqlite3 CLI accepts two distinct command grammars inside its interactive REPL and batch streams: standard SQL statements and meta dot-commands. Every SQL statement (SELECT, INSERT, CREATE TABLE, PRAGMA, EXPLAIN QUERY PLAN) is parsed by the core SQLite engine and MUST terminate with a semicolon (;). If you press Enter without typing a semicolon, the prompt changes from sqlite> to ...> to indicate a multi-line SQL continuation.

Conversely, dot-commands (such as .tables, .schema, .mode, .headers, .import, .dump, and .quit) are interpreted purely by the sqlite3 command-line shell wrapper rather than the SQL parser. Dot-commands must begin with a period (.) at column 0 of the line and MUST NOT end with a semicolon (appending a semicolon to .tables; causes the shell to look for a table literally named ';').

  • 0 — Interactive session or batch SQL execution completed cleanly without errors.
  • 1 — SQL syntax error, constraint violation, locked database timeout (SQLITE_BUSY), or file I/O failure.
  • 2 — Invalid command-line option or misused shell invocation arguments.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-box-boxFormats query output inside clean Unicode box-drawing tables with column headers automatically enabled.
-csv-csvSets the output mode to RFC 4180 Comma-Separated Values (CSV) for clean data export and spreadsheet ingestion.
-json-jsonOutputs query results as a valid JSON array of objects, ideal for piping directly into jq or REST APIs.
-header-header / -noheaderTurns column name headers on or off at the top of tabular, CSV, or column query outputs.
-readonly-readonlyOpens the database file in strict read-only mode, preventing accidental writes or schema modifications during production debugging.
-bail-bailStops execution immediately and exits with a non-zero status code upon encountering the first SQL error in non-interactive batch mode.
-cmd-cmd COMMANDExecutes the specified dot-command or SQL statement (e.g., -cmd 'PRAGMA busy_timeout=5000;') before processing subsequent inputs.
-batch-batchForces non-interactive batch processing mode even when standard input is attached to a terminal device.
-init-init FILEReads and executes startup SQL settings and dot-commands from FILE before entering interactive mode.

When querying a live production SQLite database from a terminal or cron script, three flags should be treated as mandatory best practices: -readonly (when only inspecting data, so a typo cannot mutate production tables), -bail (so multi-statement batch scripts halt immediately on the first failed statement), and -cmd 'PRAGMA busy_timeout=5000;' (which tells sqlite3 to wait up to 5,000 milliseconds for an active write lock to clear instead of failing instantaneously with Error: database is locked).

Advertisement

For display formatting, SQLite 3.33+ introduced -box, -table, and -json. Historically, sysadmins had to pass -header -column to get readable output, which often truncated wide strings. Today, passing -box on the command line or running .mode box interactively renders crisp, auto-sized Unicode tables with zero truncation.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Create a Database, Enable WAL Mode, and Insert Initial Records

Create a new SQLite database file named inventory.db, enable Write-Ahead Logging and foreign key enforcement, create a table, and insert sample rows non-interactively.

sqlite3 inventory.db << 'EOF'
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS servers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  hostname TEXT NOT NULL UNIQUE,
  ip_addr TEXT NOT NULL,
  role TEXT DEFAULT 'worker',
  cpu_cores INTEGER CHECK(cpu_cores > 0)
);
INSERT INTO servers (hostname, ip_addr, role, cpu_cores) VALUES
  ('web-prod-01', '10.24.10.11', 'ingress', 8),
  ('db-prod-01',  '10.24.20.50', 'database', 32),
  ('app-prod-01', '10.24.15.21', 'worker', 16);
EOF

# Illustrative output (reviewed against documentation)
wal

Passing a heredoc (<< 'EOF') into sqlite3 executes the entire SQL script in a single process invocation. Setting PRAGMA journal_mode=WAL; persists in the database header across future connections.

2. Query Database Rows with Unicode Box and JSON Formatting

Run non-interactive SELECT queries using the -box flag for human-readable terminal inspection and the -json flag for programmatic pipelines.

sqlite3 -readonly -box inventory.db "SELECT id, hostname, ip_addr, role, cpu_cores FROM servers ORDER BY cpu_cores DESC;"
sqlite3 -readonly -json inventory.db "SELECT hostname, ip_addr FROM servers WHERE role = 'database';"

# Illustrative output (reviewed against documentation)
┌────┬─────────────┬─────────────┬──────────┬───────────┐
│ id │  hostname   │   ip_addr   │   role   │ cpu_cores │
├────┼─────────────┼─────────────┼──────────┼───────────┤
│ 2  │ db-prod-01  │ 10.24.20.50 │ database │ 32        │
│ 3  │ app-prod-01 │ 10.24.15.21 │ worker   │ 16        │
│ 1  │ web-prod-01 │ 10.24.10.11 │ ingress  │ 8         │
└────┴─────────────┴─────────────┴──────────┴───────────┘
[{"hostname":"db-prod-01","ip_addr":"10.24.20.50"}]

Adding -readonly guarantees that your diagnostic query cannot modify the database file, while -box and -json eliminate the need for custom formatting scripts.

3. Inspect Tables, Indexes, and Full DDL Schema Using Dot-Commands

Execute the .tables, .indexes, and .schema dot-commands to reverse-engineer an unfamiliar SQLite database's structure.

sqlite3 -readonly inventory.db ".tables"
sqlite3 -readonly inventory.db ".schema servers"

# Illustrative output (reviewed against documentation)
servers
CREATE TABLE servers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  hostname TEXT NOT NULL UNIQUE,
  ip_addr TEXT NOT NULL,
  role TEXT DEFAULT 'worker',
  cpu_cores INTEGER CHECK(cpu_cores > 0)
);

Dot-commands can be passed directly as quoted arguments on the command line just like SQL queries, making it fast to inspect schema definitions without entering the interactive REPL.

4. Export Query Results to a Standard CSV File

Combine the -header and -csv flags (or use .mode csv and .once inside the shell) to export filtered database records to a CSV file.

sqlite3 -readonly -header -csv inventory.db "SELECT hostname, ip_addr, role, cpu_cores FROM servers;" > servers_export.csv
cat servers_export.csv

# Illustrative output (reviewed against documentation)
hostname,ip_addr,role,cpu_cores
web-prod-01,10.24.10.11,ingress,8
db-prod-01,10.24.20.50,database,32
app-prod-01,10.24.15.21,worker,16

The -csv flag properly quotes fields containing commas, double quotes, or newlines in compliance with RFC 4180.

5. Import a CSV File Directly into a SQLite Table

Use the .import dot-command with --csv and --skip 1 to bulk-load rows from an external CSV file into an existing table while skipping the header row.

cat << 'EOF' > new_nodes.csv
hostname,ip_addr,role,cpu_cores
cache-prod-01,10.24.30.10,cache,8
worker-prod-02,10.24.15.22,worker,16
EOF
sqlite3 inventory.db ".import --csv --skip 1 new_nodes.csv servers_staging"
sqlite3 -box inventory.db "SELECT * FROM servers_staging;"

# Illustrative output (reviewed against documentation)
┌───────────────┬─────────────┬────────┬───────────┐
│   hostname    │   ip_addr   │  role  │ cpu_cores │
├───────────────┼─────────────┼────────┼───────────┤
│ cache-prod-01 │ 10.24.30.10 │ cache  │ 8         │
│ worker-prod-02│ 10.24.15.22 │ worker │ 16        │
└───────────────┴─────────────┴────────┴───────────┘

If the target table (servers_staging) does not exist yet, .import --csv without --skip 1 automatically reads the first row of the CSV file and creates the table using those column names.

6. Analyze Query Performance with EXPLAIN QUERY PLAN

Verify whether a slow SQLite query is performing a full table scan (SCAN) or utilizing a B-tree index (SEARCH) using EXPLAIN QUERY PLAN.

sqlite3 -readonly inventory.db "EXPLAIN QUERY PLAN SELECT * FROM servers WHERE hostname = 'db-prod-01';"
sqlite3 -readonly inventory.db "EXPLAIN QUERY PLAN SELECT * FROM servers WHERE role = 'worker';"

# Illustrative output (reviewed against documentation)
QUERY PLAN
`--SEARCH servers USING INDEX sqlite_autoindex_servers_1 (hostname=?)
QUERY PLAN
`--SCAN servers

Lookups on hostname use the automatic unique B-tree index (SEARCH), whereas filtering by role performs a sequential full-table SCAN because no index exists on the role column.

Real-World Workflows, Pipelines, and Shell Automation

Safe Online Hot Backup and Integrity Verification Pipeline

Never copy an active SQLite database using cp or rsync alone, because copying the main file while a transaction is mid-flight in the -wal file produces a corrupted backup. Instead, use SQLite's built-in online backup API via .backup (or VACUUM INTO) and verify the backup with PRAGMA integrity_check.

#!/usr/bin/env bash
set -euo pipefail

SRC_DB="inventory.db"
BACKUP_DB="inventory_backup_$(date -u +%Y%m%d_%H%M%S).sqlite"

sqlite3 -bail -cmd "PRAGMA busy_timeout=10000;" "${SRC_DB}" ".backup '${BACKUP_DB}'"
INTEGRITY=$(sqlite3 -readonly "${BACKUP_DB}" "PRAGMA integrity_check;")

if [ "${INTEGRITY}" = "ok" ]; then
  echo "[OK] Online backup verified: ${BACKUP_DB} (integrity_check=ok)"
else
  echo "[ERROR] Backup integrity check failed: ${INTEGRITY}" >&2
  exit 1
fi

# Illustrative output (reviewed against documentation)
[OK] Online backup verified: inventory_backup_20261022_183000.sqlite (integrity_check=ok)

The .backup dot-command acquires a shared lock, copies database pages safely while allowing concurrent application reads, and automatically restarts page copying if a concurrent writer modifies the source database.

Full SQL Text Dump and Compressed Disaster Recovery Archive

Use the .dump dot-command to serialize the entire database schema and data as portable SQL statements, and pipe it directly through gzip for version-controlled archival.

sqlite3 -readonly -cmd "PRAGMA busy_timeout=5000;" inventory.db ".dump" | gzip -9 > inventory_dump.sql.gz
zcat inventory_dump.sql.gz | head -n 12

# Illustrative output (reviewed against documentation)
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE servers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  hostname TEXT NOT NULL UNIQUE,
  ip_addr TEXT NOT NULL,
  role TEXT DEFAULT 'worker',
  cpu_cores INTEGER CHECK(cpu_cores > 0)
);
INSERT INTO servers VALUES(1,'web-prod-01','10.24.10.11','ingress',8);
INSERT INTO servers VALUES(2,'db-prod-01','10.24.20.50','database',32);
INSERT INTO servers VALUES(3,'app-prod-01','10.24.15.21','worker',16);

To restore a .dump archive into a brand-new database file later, simply run zcat inventory_dump.sql.gz | sqlite3 restored_inventory.db.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding sqlite3 inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Because an entire SQLite database resides in a single regular file, access control is governed completely by Linux filesystem permissions (chown and chmod). Importantly, when SQLite runs in default rollback journal mode or WAL mode, the process executing sqlite3 (or your web application) requires write (w) and execute (x) permissions not only on the .db file itself, but also on the parent directory so it can create and unlink temporary -journal, -wal, and -shm files.

When invoking sqlite3 from shell scripts with user-supplied variables, never interpolate untrusted bash variables directly into SQL strings (e.g., sqlite3 app.db "SELECT * FROM users WHERE name = '$USER_INPUT';"), which exposes your script to classic SQL injection AND shell metacharacter injection. Use SQLite's .param set :key value feature in modern SQLite 3.28+ to bind parameters safely.

GNU/Linux, BSD, and BusyBox Implementation Differences

The sqlite3 CLI is cross-platform and available across Debian/Ubuntu (apt install sqlite3), RHEL/Rocky/Fedora (dnf install sqlite), Arch, Alpine, macOS (pre-installed at /usr/bin/sqlite3), and BSD. However, older Enterprise Linux distributions shipping SQLite prior to version 3.33 do not support the modern -box, -table, or -json flags; on those older hosts, use -header -column for tabular display.

Additionally, interactive command history and arrow-key line editing in the sqlite3 REPL depend on whether the binary was compiled against libedit or GNU readline. On minimal containers where arrow keys print raw escape sequences like ^[[A, install rlwrap or use the full distribution sqlite3 package.

Troubleshooting Common Errors and Diagnostics

Runtime error: database is locked (5)

Root Cause: Another process holds an active write transaction lock on the database file, and by default the sqlite3 CLI waits 0 milliseconds before failing with SQLITE_BUSY.

Resolution: Pass -cmd 'PRAGMA busy_timeout=5000;' when invoking sqlite3 so it waits up to 5 seconds for the concurrent transaction to commit, and ensure the database is configured with PRAGMA journal_mode=WAL;.

sqlite3 -cmd 'PRAGMA busy_timeout=5000;' inventory.db 'SELECT COUNT(*) FROM servers;'

Runtime error: attempt to write a readonly database (8)

Root Cause: Either the user running sqlite3 lacks write permissions on the .db file, OR the user has write permissions on the .db file itself but lacks write permissions on the parent directory (which SQLite requires to create its -journal or -wal lock files).

Resolution: Inspect permissions on both the database file and its containing directory using ls -ld, and grant appropriate group or user write permissions to the directory as well.

ls -ld /var/lib/myapp /var/lib/myapp/app.db
sudo chown -R appuser:appgroup /var/lib/myapp
sudo chmod 0775 /var/lib/myapp

Error: unknown command or invalid arguments: "tables;". Enter ".help" for help

Root Cause: You appended a trailing SQL semicolon to a CLI dot-command (typing .tables; instead of .tables).

Resolution: Omit the semicolon at the end of any command starting with a period (.tables, .schema, .mode, .quit); semicolons are only used to terminate SQL statements.

sqlite3 -readonly inventory.db '.tables'

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Type .quit or .exit (with a leading period and no semicolon) and press Enter, or press Ctrl+D (EOF) on an empty line. If you are stuck on a continuation prompt (...>) because you started typing a SQL statement without a closing quote or semicolon, type a closing semicolon (;) or press Ctrl+C first, then run .quit.
By design, sqlite3 defers creating the physical file on disk until the first schema or data modification occurs. If you run sqlite3 test.db and immediately exit with .quit without creating a table or running PRAGMA user_version=1;, no file is written. To force creation of an empty database file, run sqlite3 test.db 'VACUUM;'.
Create a configuration file at ~/.sqliterc containing .headers on and .mode box (or .mode column on older SQLite versions). Every time you launch an interactive sqlite3 session, it automatically reads ~/.sqliterc and applies your preferred display settings.
No. If an application is actively writing to the database or using WAL mode, copying only the .db file with cp or scp can capture partially flushed pages or miss committed frames still residing in the .db-wal file, resulting in a corrupted backup. Always use sqlite3 mydb.db ".backup 'backup.db'" or sqlite3 mydb.db "VACUUM INTO 'backup.db';".
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout