How to Create Your First SQLite Database and Table
SQLite is the friendliest database to learn with: no server to install, no passwords, and the whole database is a single file. This how-to gets you from nothing to a table with data in it.
What you need
- a computer running Windows, macOS or Linux
- the SQLite command-line tool, or a graphical tool such as DB Browser for SQLite
- about fifteen minutes
macOS and most Linux systems include the sqlite3 command already. On Windows, download the command-line tools from the official SQLite website, or install a graphical tool if you prefer clicking to typing.
Steps
- Open a terminal (Command Prompt or PowerShell on Windows) in a folder where you keep practice work.
- Create and open a database file:
sqlite3 library.db
If library.db does not exist, SQLite creates it. You will see a sqlite> prompt.
- Create a table:
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT,
year INTEGER
);
End every SQL statement with a semicolon. Without it, SQLite waits for more input.
- Add some rows:
INSERT INTO books (title, author, year) VALUES ('Gardens of Rain', 'Ada North', 2019);
INSERT INTO books (title, author, year) VALUES ('Paper Moon', 'Ben Okoro', 2022);
You do not give an id; SQLite fills it in.
- Read them back:
SELECT * FROM books;
- Make the output easier to read with two SQLite settings:
.headers on
.mode column
Commands starting with a dot are instructions to the SQLite tool itself, not SQL.
- Leave with
.quit. Your data is saved inlibrary.db.
How to check it worked
- Run
sqlite3 library.dbagain and thenSELECT * FROM books;. Your two books should still be there. - Type
.tablesto list the tables in the file. You should seebooks. - Type
.schema booksto see the CREATE TABLE statement SQLite stored.
Common problems
| Problem | Likely cause | Fix |
|---|---|---|
| Nothing happens after a statement | Missing semicolon | Type ; and press Enter |
| "no such table: books" | You opened a different file, or misspelt the name | Check the folder and file name |
| "NOT NULL constraint failed" | You left out the title | Every book needs a title |
| "command not found: sqlite3" | Tool not installed or not on your path | Install it, or use a graphical tool |
Next steps
Try a few SELECT queries from SELECT queries in five short modules, then connect to this same file from a Python script. When you want a fresh start, simply delete library.db and begin again; that freedom is exactly why SQLite is great for learning.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.