Database Your First Database with SQLite
What you will learn
- Create a database file and a table
- Add, read, change and delete rows (the CRUD operations)
- Prove data lasts after closing
- Look at the structure of a table
1. Why SQLite for learning
SQLite comes with Python (import sqlite3), needs no installation or server, and keeps a database in one file. It is a real SQL database, used widely, so what you learn here carries over. It does differ from PostgreSQL and MySQL in places (for example it is relaxed about column types), and these lessons point out differences when they matter.
2. Create and fill a table
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "first.db")
con = sqlite3.connect(path)
con.execute("""CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER)""")
con.executemany("INSERT INTO books (title, author, year) VALUES (?, ?, ?)",
[("Rain Songs", "A. Karim", 2011), ("River Maps", "N. Das", 2018), ("Night Train", "A. Karim", 2020)])
con.commit()
for row in con.execute("SELECT * FROM books"):
print(row)
(1, 'Rain Songs', 'A. Karim', 2011)
(2, 'River Maps', 'N. Das', 2018)
(3, 'Night Train', 'A. Karim', 2020)
id INTEGER PRIMARY KEYgives each book a unique number, filled in automatically (chapter 2).NOT NULLmakes title and author required.executemanyruns one statement for several rows.- The books and authors are made up.
3. Ask questions
print(con.execute("SELECT title FROM books WHERE author = 'A. Karim' ORDER BY year DESC").fetchall())
[('Night Train',), ('Rain Songs',)]
4. Change and delete
con.execute("UPDATE books SET year = 2019 WHERE title = 'River Maps'")
con.execute("DELETE FROM books WHERE title = 'Night Train'")
con.commit(); con.close()
Always include a WHERE in UPDATE and DELETE; without it they affect every row.
5. Prove it lasts
Open the file again as if the program had been restarted:
con = sqlite3.connect(path)
print(con.execute("SELECT title, year FROM books").fetchall())
[('Rain Songs', 2011), ('River Maps', 2019)]
The update and the delete are both there.
6. Look at the structure
print(con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall())
print(con.execute("PRAGMA table_info(books)").fetchall())
[('books',)]
[(0, 'id', 'INTEGER', 0, None, 1), (1, 'title', 'TEXT', 1, None, 0), (2, 'author', 'TEXT', 1, None, 0), (3, 'year', 'INTEGER', 0, None, 0)]
sqlite_master is a built-in table listing what the database contains. PRAGMA table_info lists each column: its position, name, type, whether it is NOT NULL (1) and whether it is part of the primary key (1). These commands are specific to SQLite; other systems have their own ways of showing structure.
Try the same statements as SQL cells
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The Python above works on a database file; a SQL cell works on the sample data in your browser. The statements are the same. The books table is a small one of its own; Reset data removes it.
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER);
INSERT INTO books (title, author, year) VALUES
('Rain Songs', 'A. Karim', 2011), ('River Maps', 'N. Das', 2018), ('Night Train', 'A. Karim', 2020);
SELECT * FROM books;
id title author year
-- ----------- -------- ----
1 Rain Songs A. Karim 2011
2 River Maps N. Das 2018
3 Night Train A. Karim 2020
(3 rows)
Ask a question:
SELECT title FROM books WHERE author = 'A. Karim' ORDER BY year DESC;
title
-----------
Night Train
Rain Songs
(2 rows)
Change and delete (with a WHERE):
UPDATE books SET year = 2019 WHERE title = 'River Maps';
DELETE FROM books WHERE title = 'Night Train';
SELECT title, year FROM books;
title year
---------- ----
Rain Songs 2011
River Maps 2019
(2 rows)
Look at the structure:
SELECT name, type, "notnull", pk FROM pragma_table_info('books');
name type notnull pk
------ ------- ------- --
id INTEGER 0 1
title TEXT 1 0
author TEXT 1 0
year INTEGER 0 0
(4 rows)
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER);
INSERT INTO books (title, author, year) VALUES
('Rain Songs', 'A. Karim', 2011), ('River Maps', 'N. Das', 2018), ('Night Train', 'A. Karim', 2020);
SELECT * FROM books;
id title author year
-- ----------- -------- ----
1 Rain Songs A. Karim 2011
2 River Maps N. Das 2018
3 Night Train A. Karim 2020
(3 rows)
Ask a question:
SELECT title FROM books WHERE author = 'A. Karim' ORDER BY year DESC;
title
-----------
Night Train
Rain Songs
(2 rows)
Change and delete (with a WHERE):
UPDATE books SET year = 2019 WHERE title = 'River Maps';
DELETE FROM books WHERE title = 'Night Train';
SELECT title, year FROM books;
title year
---------- ----
Rain Songs 2011
River Maps 2019
(2 rows)
Look at the structure:
SELECT name, type, "notnull", pk FROM pragma_table_info('books');
name type notnull pk
------ ------- ------- --
id INTEGER 0 1
title TEXT 1 0
author TEXT 1 0
year INTEGER 0 0
(4 rows)
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER);
INSERT INTO books (title, author, year) VALUES
('Rain Songs', 'A. Karim', 2011), ('River Maps', 'N. Das', 2018), ('Night Train', 'A. Karim', 2020);
SELECT * FROM books;
id title author year
-- ----------- -------- ----
1 Rain Songs A. Karim 2011
2 River Maps N. Das 2018
3 Night Train A. Karim 2020
(3 rows)
Ask a question:
SELECT title FROM books WHERE author = 'A. Karim' ORDER BY year DESC;
title
-----------
Night Train
Rain Songs
(2 rows)
Change and delete (with a WHERE):
UPDATE books SET year = 2019 WHERE title = 'River Maps';
DELETE FROM books WHERE title = 'Night Train';
SELECT title, year FROM books;
title year
---------- ----
Rain Songs 2011
River Maps 2019
(2 rows)
Look at the structure:
SELECT name, type, "notnull", pk FROM pragma_table_info('books');
name type notnull pk
------ ------- ------- --
id INTEGER 0 1
title TEXT 1 0
author TEXT 1 0
year INTEGER 0 0
(4 rows)
What a cell cannot show is the "prove it lasts" step: closing the program and opening the file again. That needs a real file, which is what the Python above does.
Worked example: your own little library
Try this yourself: create a members table with id, name (required) and joined (a year), insert three members, update one, delete one, then reopen the file and list them. Following sections 2 to 5, it takes about ten lines. Check your list matches what you expected, and that reopening shows the same rows.
Running examples in your browser
Under many Python examples on this site there is a Try it button. It runs the example with Python inside your browser (a version of Python called Pyodide), so nothing has to be installed. It includes sqlite3, so the examples in this course work there too.
The SQLite inside the browser can be older than the one on a computer. The outputs in these lessons were produced with SQLite 3.50.4. The browser box we tested uses SQLite 3.39.0. Most results are identical, but a few differ:
| What | On a computer (SQLite 3.50.4) | In the browser box (SQLite 3.39.0) |
|---|---|---|
SELECT date('2026-02-30') |
2026-03-02 |
2026-02-30 (returned unchanged) |
The third number of an EXPLAIN QUERY PLAN row |
for example 56 |
0 |
sqlite3.sqlite_version |
3.50.4 |
3.39.0 |
Every timing differs too, because the browser is slower than a normal Python and varies from machine to machine. The box always shows the result of your own run, so when it differs from the lesson, the lesson's wording about what the result means is still right. A few features may be missing in the browser version, and some examples use files, so run the lesson's "setup" block on the same page first if a later block complains.
Common mistakes
- Forgetting
commit()beforeclose(), losing the changes. UPDATEorDELETEwithoutWHERE.- Creating the table twice (it fails); use
CREATE TABLE IF NOT EXISTSwhen a script may run again. - Expecting the file name to be created in the folder you expect. A relative path depends on where the program runs.
Key takeaways
sqlite3gives you a real SQL database in a file with no setup.- Create, read, update and delete are the four basic operations.
- Always commit and always use
WHEREwhen changing or deleting. - Reopening the file proves the data lasts.
Practice
1. What do CRUD letters stand for?
Show answer
Create, Read, Update, Delete.
2. What does NOT NULL do to the title column?
Show answer
It makes the title required; inserting a book without one is refused.
3. What would DELETE FROM books (no WHERE) do?
Show answer
Delete every row in the table.
4. Why did the results after reopening still show the update?
Show answer
The change was committed and saved in the file before the connection closed.
5. What does executemany do?
Show answer
Runs the same statement once for each set of values in a list.
6. Write the SQL to list the titles of books published after 2015.
Show answer
SELECT title FROM books WHERE year > 2015