A small SQLite dataset

Lesson 2 of 18 · SQL foundations

The examples use SQLite 3.39 or newer. SQLite is embedded; no server is required. To run them with the SQLite command-line shell, start sqlite3 practice.db in a disposable directory, paste the setup below, then paste individual queries. Exit with .quit. The file is local and may be deleted when finished. Do not point examples at a real database. Alternatively a SQLite client can execute the same statements.

The shell is a separate program from SQLite’s library; installing one does not necessarily install the other. Run sqlite3 --version in a terminal to check the shell and its version. If the command is unavailable, install the SQLite command-line tools for your operating system or use a client with a compatible SQLite library. A shell prompt is not SQL: enter .quit in the shell, but enter SQL statements ending in semicolons. If you reopen the database, enable foreign keys again for the new connection.

Run this setup once in a fresh database. Foreign-key enforcement is enabled per connection, before a transaction begins:

PRAGMA foreign_keys = ON;
CREATE TABLE shelves (id INTEGER PRIMARY KEY, label TEXT NOT NULL UNIQUE);
CREATE TABLE books (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  shelf_id INTEGER REFERENCES shelves(id),
  pages INTEGER CHECK (pages > 0),
  published INTEGER NOT NULL DEFAULT 1 CHECK (published IN (0, 1))
);
INSERT INTO shelves (id, label) VALUES (1, 'Nature'), (2, 'History'), (3, 'Art');
INSERT INTO books (id, title, shelf_id, pages, published) VALUES
  (1, 'Moss Atlas', 1, 120, 1),
  (2, 'River Notes', 1, 80, 1),
  (3, 'Clay Roads', 2, 200, 0),
  (4, 'Night Sky', NULL, NULL, 1);

Each later example starts from these rows unless it says otherwise. NULL means missing or unknown, not zero or an empty string. INTEGER PRIMARY KEY is special in SQLite: omitting its value normally assigns a rowid automatically. SQLite’s AUTOINCREMENT keyword adds a stronger non-reuse rule and overhead; it is not needed for ordinary automatic IDs. Other databases use different identity mechanisms.

To reset after a change, close the shell, remove the disposable practice.db file using your file manager or terminal, reopen a new file, and run the setup again. This destroys that file’s data; check its location and name first. Never use this reset on a database you need to keep.

Chapter index · Course index