SQLite Command Line
The sqlite3 Program
sqlite3 is the command line program for SQLite. With it, you can open a database, run SQL statements and look at the result. Read how to install it in the SQLite Get Started chapter.
Start sqlite3 with the name of a database file:
sqlite3 northwind.db
You get the prompt sqlite>, where you can type SQL statements. End each statement with a semicolon. If a statement continues on the next line, the prompt changes to ...>.
Dot Commands
Commands that start with a dot are special commands for sqlite3, not SQL. They do not end with a semicolon:
| Command | Description |
|---|---|
.help | Shows all the dot commands |
.open FILE | Opens a database file, and creates it if it does not exist |
.tables | Lists the tables |
.schema TABLE | Shows the CREATE statement of a table |
.headers on | Shows the column names in the result |
.mode MODE | Sets the output format, like list, column, box, table, csv, json or markdown |
.read FILE | Runs the SQL statements in a file |
.output FILE | Writes the results to a file. .output stdout writes to the screen again |
.import FILE TABLE | Imports data from a file into a table |
.dump | Writes the whole database as SQL statements |
.databases | Lists the attached databases |
.quit | Closes sqlite3 |
Easy to Read Results
By default, sqlite3 shows each record on one line, with the values separated by |, and without the column names:
sqlite> SELECT * FROM Shippers;
1|Speedy Express|(503) 555-9831
2|United Package|(503) 555-3199
3|Federal Shipping|(503) 555-9931
These two commands make the results much easier to read:
sqlite> .headers on
sqlite> .mode box
sqlite> SELECT * FROM Shippers;
┌───────────┬──────────────────┬────────────────┐
│ ShipperID │ ShipperName │ Phone │
├───────────┼──────────────────┼────────────────┤
│ 1 │ Speedy Express │ (503) 555-9831 │
│ 2 │ United Package │ (503) 555-3199 │
│ 3 │ Federal Shipping │ (503) 555-9931 │
└───────────┴──────────────────┴────────────────┘
.headers on shows the column names, and .mode box draws lines around the values.
Run SQL Without the Prompt
You can give sqlite3 an SQL statement directly. It prints the result, and stops:
sqlite3 northwind.db "SELECT COUNT(*) FROM Customers;"
91
You can also save SQL statements in a file, and run them all at once. Here is a file named script.sql, with two statements:
SELECT COUNT(*) FROM Customers;
SELECT CustomerName FROM Customers
WHERE Country = 'UK';
Run the file like this. The results of the statements are printed one after the other:
sqlite3 northwind.db < script.sql
91
Around the Horn
B's Beverages
Consolidated Holdings
Eastern Connection
Island Trading
North/South
Seven Seas Imports
Note: Windows PowerShell does not support <. There, write sqlite3 northwind.db ".read script.sql" instead.