A database in one file

Use the SQLite shell

Open a database, run SQL, and use dot commands to inspect the shell without confusing them with SQL statements.

Open a database file from the terminal:

sqlite3 notes.db

You’re now inside the shell, and everything you type goes to one of two interpreters. Knowing which one you’re talking to saves a lot of confusion.

SQL statements such as SELECT 1; end with a semicolon. If you press enter without one, the shell shows a continuation prompt (...>) and waits — it thinks your statement isn’t finished. Type the missing ; and press enter.

Dot commands start with a dot, belong to the shell itself, take no semicolon, and must fit on one line. Try .databases, .tables, .schema, and .help.

sqlite> .tables
notes
sqlite> .schema notes
CREATE TABLE notes (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL
) STRICT;

.tables lists what exists. .schema prints the exact SQL that created it — this is how you inspect any unfamiliar SQLite file. .databases shows the full path of the open file, which settles any doubt about which database you’re actually in.

Make query output readable

The default output is bare values separated by |. Two settings make it much friendlier:

sqlite> .headers on
sqlite> .mode box
sqlite> SELECT id, title FROM notes;
┌────┬───────────────┐
│ id │     title     │
├────┼───────────────┤
│ 1  │ Plan the week │
└────┴───────────────┘

These settings last for the session. Leave with .quit and they reset.

Run a query without entering the shell

You can also pass SQL directly as an argument, which is handy in scripts:

sqlite3 notes.db "SELECT count(*) FROM notes;"
# 1

The shell runs the query, prints the result, and exits.

The classic mistake here is mixing the two languages: typing .tables; (dot command with a semicolon) or SELECT 1 (SQL without one). The first prints an error, the second leaves you stuck at the ...> continuation prompt. If the shell seems to hang, look at the prompt — ...> means it’s waiting for your semicolon, and typing ; on its own line finishes the statement.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →