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.
12 min read
Learn sqlite3 command line with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What sqlite3 Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
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.
The sqlite3 command line tool is an interactive terminal client and batch execution engine for creating, inspecting, and querying serverless SQLite database files on Linux. Run sqlite3 app.db to launch an interactive SQL shell, use dot-commands like .tables and .schema to inspect metadata, or pass a SQL query as a second argument (sqlite3 -box app.db 'SELECT * FROM users;') for non-interactive scripting.
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.
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:
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 / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-box | -box | Formats query output inside clean Unicode box-drawing tables with column headers automatically enabled. |
-csv | -csv | Sets the output mode to RFC 4180 Comma-Separated Values (CSV) for clean data export and spreadsheet ingestion. |
-json | -json | Outputs query results as a valid JSON array of objects, ideal for piping directly into jq or REST APIs. |
-header | -header / -noheader | Turns column name headers on or off at the top of tabular, CSV, or column query outputs. |
-readonly | -readonly | Opens the database file in strict read-only mode, preventing accidental writes or schema modifications during production debugging. |
-bail | -bail | Stops execution immediately and exits with a non-zero status code upon encountering the first SQL error in non-interactive batch mode. |
-cmd | -cmd COMMAND | Executes the specified dot-command or SQL statement (e.g., -cmd 'PRAGMA busy_timeout=5000;') before processing subsequent inputs. |
-batch | -batch | Forces non-interactive batch processing mode even when standard input is attached to a terminal device. |
-init | -init FILE | Reads 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).
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
Never store or open an active read-write SQLite database over network filesystems such as NFS or SMB/CIFS whose POSIX fcntl() byte-range locking implementations are buggy or cached; doing so is the number one cause of unrecoverable database corruption (SQLITE_CORRUPT). Furthermore, never delete the companion -wal or -shm files while a database has uncommitted WAL frames, or you will permanently lose recent transactions.
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'
Alternatives, Related Commands, and Related Tutorials
- mkdir Command in Linux: Create Directories & Parent Trees — Practical syntax, flags, and examples for
mkdir. - chown Command in Linux: Change File & Directory Ownership — Practical syntax, flags, and examples for
chown. - How to Unzip Files in Linux: Extract, List & Exclude Guide — Practical syntax, flags, and examples for
unzip. - dd Command in Linux: Disk Cloning, Backup & Wiping Guide — Practical syntax, flags, and examples for
dd. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
~/.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.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!