Loading

T11 SQL · Lesson 1

Databases and tables

A database keeps records in tables that a program can search for you. Meet SQLite and its sqlite3 command, make a table with CREATE TABLE, fill it with INSERT, read it back with SELECT, and learn what SQLite does with each kind of value.

  • say what a database, a table, a row and a column are, and why a table beats a loose list
  • run SQL with sqlite3 three ways: in quotes, from a file, and from a here-document
  • make a table with CREATE TABLE, choosing a name and a type for each column
  • add rows with INSERT, one or many at a time, with text in single quotes
  • read a table back with SELECT, all its columns or the ones you name
  • read SQLite's error messages and fix the mistakes they point at
About 70 minutesChecked against SQLite's command-line shell, sqlite3, the "sqlite-tools-linux-x64-3540100.zip" of sqlite.org (the kit compares every SQL block with it, in its sandbox; the page runs the small sqlite3 of plan 34) 3.54.1 (2026-11-21); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-21)Play this lesson's games

The back cover

A program forgets its data the moment it stops, and a file keeps data without understanding it. Ask a file how many gauges read above ninety, and somebody still has to read every line. A database keeps its records and answers questions about them by itself.

These pages open the SQL track with SQLite, a database kept in a single file. They meet tables, rows and columns, run SQL with the sqlite3 command, make a table with CREATE TABLE, fill it with INSERT and read it back with SELECT. They also meet the five kinds of value SQLite stores, and the short, exact messages it gives when something goes wrong.

Before you start

The story: Sheets in every drawer

Next door to the Testing House stands the Ledger-keepers' Hall, a long room of shelves and green-shaded lamps. Every hall of the city sends its records here: which gauges it has, where they stand, what they read. You find the records on loose sheets, a different shape in every drawer.

The Engine Hall writes its gauges as a list of names. The Couriers' Yard writes the same gauges as a paragraph, and a third clerk draws a box around each one. When a hall asks how many gauges read above ninety, three clerks spend the morning reading sheets and give three different answers.

Registrar Nadia Folio closes the last drawer. "Ask the ledger, not your memory," she says. "Rule one page into columns, give every column a name and a kind, and write one gauge on each line. Then the ledger can answer for itself."

Every lesson so far kept its data in a program. The gauges server of T9 held its gauges in an array, and the array was gone the moment the server stopped. A file can keep data after a program stops, as the JSON files of T8 did. But a file only keeps data. It cannot answer a question about it.

A database keeps data and answers questions about it. You hand it a question written in a small language, and it searches its own records and hands back the answer. That small language is SQL, short for Structured Query Language. SQLite speaks it, and so do PostgreSQL, MySQL and most other databases you will meet.

This lesson starts the SQL track. It meets one database, SQLite, and its command, sqlite3. It makes a table, fills it with rows and reads them back. The next six lessons ask sharper and sharper questions of the same table.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
A table of rows and columns, as in HTML.<tr><td>boiler</td></tr>A database table has rows and columns too.
Files keep data after a program stops.cat gauges.jsonA database is kept in a file.
Running a command in the terminal.ls -lsqlite3 is a command.
Quotes in bash.echo 'two spaces'SQL goes to sqlite3 inside quotes.
Redirecting a file in with <.wc -l < notes.txtFeeding sqlite3 a file of SQL.
A here-document.cat <<'END'Typing a few statements at once.
Text and numbers are different kinds of value."96" and 96Each column has a kind.
null: a value that says nothing is there.nullSQL's NULL.
Reading an error as a clue.SyntaxError: ...SQLite's messages point at the mistake.
The exit status.echo $?sqlite3 says when something failed.

By the end of this lesson you will be able to:

  • say what a database, a table, a row and a column are, and why a table beats a loose list;
  • run SQL with sqlite3 three ways: in quotes, from a file, and from a here-document;
  • make a table with CREATE TABLE, choosing a name and a type for each column;
  • add rows with INSERT, one or many at a time, with text in single quotes;
  • read a table back with SELECT, all its columns or the ones you name;
  • read SQLite's error messages and fix the mistakes they point at.

How to follow this lesson

Each block is a file of SQL and the command that runs it, such as sqlite3 ledger.db < query.sql. Press Run and the page runs it with the real SQLite engine, built for web pages by the SQLite project itself. Edit the SQL, run it again, and watch the answer change.

Every block has also been run with the real sqlite3 program, version 3.54.1, in a real terminal. It printed exactly what you see, and it left exactly the same database file behind, byte for byte.

In one line

A database keeps records in tables and answers questions about them; SQL is the language of those questions, and sqlite3 is the command that carries them to SQLite.

What a database is

At a glance

A database is a store of records that answers questions about them.

It keeps its records in tables. A table holds one kind of thing, such as gauges, and every row of it has the same named columns, such as name, hall and reading. A program inside, the engine, keeps the tables and their rules. People never touch its files; they send it statements in SQL and get back answers, and every answer is itself a table. NULL marks a value that is not known.

Take a guess: Who first thought of keeping a business's data in tables that a program could search, and when?

Start with something you have seen. A small kirana shop in Pune keeps a khata, a long ruled notebook of who bought what on credit. Each line holds one purchase. Down the page run the same few columns: the date, the customer, the item and the amount.

Now Mrs Rao comes in and asks how much she owes. The shopkeeper runs a finger down the customer column, stops at every line with her name and adds up the amounts. The answer is in the book, but a person has to dig it out, line by line.

A database is a khata that digs out its own answers. It keeps records, and it has a program inside that searches them. You write the question, and the program does the reading and the adding. It does it in a moment, even when the book holds a million lines.

Tables, rows and columns

A database keeps its records in tables. A table is one ruled page of the khata: one kind of thing, written the same way on every line. A shop might keep three tables: one of customers, one of items and one of purchases.

Row

One line of a table: one record, such as one gauge or one purchase. Rows go across.

Column

One named box that every row fills in, such as the name or the amount. Columns go down. A column has a name and a kind of value, such as text or a number.

Value

What one row holds in one column: the word boiler, the number 96.5. Some lessons call it a cell, as a spreadsheet does.

Here is the Ledger-keepers' first table, the gauges of the city, as SQLite prints it. Press Run to ask for it yourself; the statement inside, SELECT, gets its own section later in this lesson.

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────────┬────────────────┬──────┬─────────╮
│ id │   name   │      hall      │ unit │ reading │
╞════╪══════════╪════════════════╪══════╪═════════╡
│  1 │ boiler   │ Engine Hall    │ C    │    96.5 │
│  2 │ pump     │ Engine Hall    │ bar  │     4.2 │
│  3 │ fan      │ Engine Hall    │ rpm  │  1200.0 │
│  4 │ chimney  │ Couriers' Yard │ C    │ NULL    │
│  5 │ pendulum │ Clock Tower    │ s    │     2.0 │
╰────┴──────────┴────────────────┴──────┴─────────╯

Read it the way you read the khata. The line under the titles is a row: gauge number 1, the boiler, in the Engine Hall, measured in degrees C, reading 96.5. The titles across the top name the five columns. Every row has the same five columns, in the same order.

The chimney's reading says NULL. NULL is SQL's word for a value that is missing: nobody has read the chimney yet. It is not zero and it is not empty text. It means "not known". The SQL track comes back to NULL many times, because it behaves in its own way.

Why not a loose list?

You may wonder why we need tables at all. A JSON file or a text file can hold the same gauges. The trouble starts when you ask questions.

In a loose list, every clerk writes a little differently. One writes "boiler 96.5", another writes "Boiler: 96.5 degrees", a third forgets the unit. A program cannot search that reliably, as the clerks in the story found out. A table fixes the shape. Every row has the same columns, so every question can be answered the same way.

A database also keeps rules. You can tell it that every gauge must have a name, and it will refuse a row without one. A text file accepts anything you type into it, mistakes included.

The program inside, and the language you speak to it

The program that keeps the tables and answers questions is called the database engine. You never touch its files yourself. You send it statements in SQL, and it sends back answers or error messages.

SQL statements read almost like English. Read this one aloud: SELECT name FROM gauges; It says "select the name column from the gauges table". The words in capitals are SQL's own words, called keywords. The semicolon ends the statement, as a full stop ends a sentence.

Here is your first statement, run for real. It asks no table at all; it asks SQLite to work out a sum. The name :memory: gives sqlite3 a database that lives only in memory, so nothing is saved.

query.sql

SELECT 1 + 1;

Terminal: sqlite3 :memory: < query.sql

╭───────╮
│ 1 + 1 │
╞═══════╡
│     2 │
╰───────╯

SQLite printed a small table: one column, titled with the expression you wrote, and one row with the answer. Every answer from a database is a table, even an answer of one number. Remember that; it makes every later answer easier to read.

Worked example 1

A school keeps its library loans on loose slips like "Anu took Malgudi Days on 3 June" and "Ravi, The Jungle Book, 5 June". Design a table for them.

What we have: Two slips, written two different ways, holding the same three facts.

What we need: A table: a name for it, and named columns that every loan fills in.

The plan: Find the facts every slip holds; make each fact a column; make each slip a row.

  1. Each slip says who borrowed, which book, and when. Those are the three columns: student, book and taken_on.
  2. Each slip becomes one row. Anu's slip gives Anu, Malgudi Days, 3 June. Ravi's gives Ravi, The Jungle Book, 5 June.
  3. Name the table for what one row is about: one loan. Call it loans.

A table called loans with three columns, student, book and taken_on, and one row for each slip.

Check: Ask the questions the librarian will ask. Who has The Jungle Book? Look down the book column. What did Anu take? Look down the student column. Both work, because every row has the same columns.

Another way: Some people add a fourth column, returned_on, left as NULL until the book comes back. That is a good idea: the empty box says the book is still out.

A path that fails: Making one column called slip and copying each sentence into it. The table would have rows, but every question would mean reading sentences again, which is the problem we started with.

When you are stuck: rows and columns

If you mix up rows and columns, picture the khata. A row is one line across the page: one purchase. A column is one heading down the page: every date, or every amount.

Another way: a row is a thing (one gauge), and a column is a question you ask about every thing (what is its name?).

A common mistake

Thinking a table can hold any shape. Every row of a table has exactly the same columns. If one gauge needs an extra fact, the table needs an extra column, and every other row gets a value there too, or NULL.

Your turn

How many rows and how many columns does the gauges table above have?Tap to reveal
  1. Count the lines below the titles: boiler, pump, fan, chimney and pendulum.
  2. Count the titles across the top: id, name, hall, unit and reading.

Five rows and five columns.

Which value in the gauges table is missing, and how does the table say so?Tap to reveal
  1. Look for a box that does not hold a name or a number.

The chimney's reading. The table shows NULL there, SQL's word for a value that is not known.

Change the statement in query.sql to work out 7 times 6, and run it. What title does the column get?Tap to reveal
  1. SQL writes times as *, as JavaScript does.
  2. Write SELECT 7 * 6; and press Run.

The answer is 42, in a column titled 7 * 6: SQLite titles a column with the expression you wrote.

Did you know?

A theory in 1970

Relational databases began as a paper. IBM's own history says that in 1970 this way of storing data was only a theory, until Edgar F. Codd, a mathematician at IBM's San Jose Research Lab, published a paper about a system that could store and find information in large databases without a formal organisational structure or exact locations.

Why it fits here: It answers the topic's question: tables that a program searches began with Codd's paper at IBM in 1970.

Source: IBM: The relational database

From an idea to System R

SQL was invented at IBM too. Don Chamberlin is best known as its co-inventor with Raymond Boyce. Codd's idea still had to prove itself in practice, so in 1973 a group of programmers undertook an industrial-strength implementation of it, a project called System R.

Why it fits here: It shows where the language of this topic came from: the tables of Codd's paper needed a language, and System R put both to work.

Source: IBM: The relational database

In one line

A database is a set of tables, each a ruled page whose rows all have the same named columns; a program inside it answers SQL statements, and every answer comes back as a table.

SQLite and the sqlite3 command

At a glance

SQLite is a database engine that keeps a whole database in one ordinary file.

There is no server to start: any program carries the engine inside itself, opens the file, asks its question and closes it. The sqlite3 command is SQLite's own program for people. It takes SQL in quotes, from a file fed in with the less-than sign, or from a here-document, and prints each answer as a box at a terminal or as plain lists for other programs. Lines that start with a dot are orders for sqlite3 itself.

Take a guess: How much testing does a small library need before it can be trusted inside an aircraft's flight software?

Many databases run as a server: a program that starts with the computer, waits for requests and answers them, as the Express servers of T9 did. PostgreSQL, the database of T12, works that way. SQLite does not.

SQLite keeps a whole database in one ordinary file, and its engine is a small library that any program can carry inside itself. There is nothing to start and nothing to keep running. Open the file, ask your question, close the file. That is why it is the first database of this track: one file, one command, and the same SQL that the big servers speak.

The sqlite3 command

The sqlite3 command is SQLite's own program for people. You give it the name of a database file, then some SQL. It opens the file, runs the SQL with the engine and prints the answers.

Read this command aloud: sqlite3 ledger.db "SELECT name, reading FROM gauges;" It says: open the file ledger.db, and run this one statement. The statement goes inside double quotes, so that bash hands it to sqlite3 as one argument, spaces and all.

Terminal (ledger.db already holds the gauges table)

sqlite3 ledger.db "SELECT name, reading FROM gauges;"
╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ pump     │     4.2 │
│ fan      │  1200.0 │
│ chimney  │ NULL    │
│ pendulum │     2.0 │
╰──────────┴─────────╯

That is the first of three ways to give sqlite3 its SQL. Each one suits a different job.

The wayWhat it looks likeWhen to use it
SQL in quotessqlite3 ledger.db "SELECT * FROM gauges;"One short statement.
A file of SQLsqlite3 ledger.db < query.sqlAnything you will run again, or edit.
A here-documentsqlite3 ledger.db <<'END'A few statements typed in one go.

The second way is the one most blocks in this track use. The file query.sql holds the SQL, and the less-than sign of T6 feeds the file to sqlite3 as its input. You keep the file, change it and run it again. The third way, a here-document, feeds lines typed straight into the terminal, up to the word END:

Terminal (ledger.db already holds the gauges table)

sqlite3 ledger.db <<'END'
SELECT name, reading FROM gauges;
END
╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ pump     │     4.2 │
│ fan      │  1200.0 │
│ chimney  │ NULL    │
│ pendulum │     2.0 │
╰──────────┴─────────╯

All three printed the same table, because all three gave the engine the same statement. The way you send SQL never changes the answer.

The prompt, for typing by hand

There is a fourth way, for exploring. Run sqlite3 with only a file name, and it shows its own prompt and waits for you to type. Each statement runs when you press Enter after its semicolon. The prompt names the database file, so you always know which book is open. This session was typed by hand into a real terminal:

Typed in a real terminal, with sqlite3 3.54.1

asha@tower:~/shop$ sqlite3 ledger.db
SQLite version 3.54.1 2026-10-16 14:45:20
Enter ".help" for usage hints.
SQLite-3.54 ledger.db-> SELECT name, reading FROM gauges;
╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ pump     │     4.2 │
│ fan      │  1200.0 │
│ chimney  │ NULL    │
│ pendulum │     2.0 │
╰──────────┴─────────╯
SQLite-3.54 ledger.db-> .tables
gauges
SQLite-3.54 ledger.db-> .quit

The page cannot wait for your keyboard, so on this page sqlite3 always needs its SQL in quotes, in a file or in a here-document. On your own computer, the prompt is the quickest way to try a statement.

Dot-commands talk to sqlite3, not to SQL

The session above typed .tables and .quit. A line that starts with a dot is a dot-command. It is an order for the sqlite3 program itself, not SQL for the engine. That is why it needs no semicolon, and why other databases do not know it.

Four dot-commands are worth knowing from the start: .tables lists the tables, .schema shows the statement that made each table, .mode chooses how answers are drawn, and .quit leaves the prompt.

How answers are drawn

When sqlite3 prints to a terminal, recent versions draw each answer as a box. That began with version 3.53, in April 2026. When the output goes into a pipe or a file, sqlite3 prints plain lists instead, one row per line with a bar between the values, because another program will read them. Older versions print those lists everywhere.

Terminal (ledger.db already holds the gauges table)

sqlite3 ledger.db "SELECT name, reading FROM gauges;" | cat
boiler|96.5
pump|4.2
fan|1200.0
chimney|
pendulum|2.0

Notice the chimney. In the box, its missing reading said NULL. In the list, it is an empty space after the bar. NULL is the same in both; only the drawing differs. You can choose the drawing yourself with an option: -box, -table, -list, -csv, -json and more. -header adds the column names to a list.

Terminal (ledger.db already holds the gauges table)

sqlite3 -csv -header ledger.db "SELECT name, reading FROM gauges;"
name,reading
boiler,96.5
pump,4.2
fan,1200.0
chimney,
pendulum,2.0

CSV, short for comma-separated values, is the plain format that spreadsheets open. JSON, from T9, is what a web server would send:

Terminal (ledger.db already holds the gauges table)

sqlite3 -json ledger.db "SELECT name, reading FROM gauges WHERE id < 3;"
[{"name":"boiler","reading":96.5},
{"name":"pump","reading":4.2}]

The WHERE id < 3 at the end kept only the first two gauges. WHERE is the subject of lesson 02; here it only keeps the JSON short.

The database is one file

A database in SQLite is one ordinary file, and the shell's own tools can look at it. It is not text, so cat would show a mess. Its size and its first few bytes tell you what it is:

Terminal (ledger.db already holds the gauges table)

ls -l ledger.db
head -c 15 ledger.db; echo
-rw-r--r-- 1 asha asha 8192 Jan  1 10:00 ledger.db
SQLite format 3

Every SQLite database starts with the words "SQLite format 3". The file is 8192 bytes: two pages of 4096 bytes each, one for the list of tables and one for the gauges. SQLite reads and writes a database a page at a time, as you would turn the pages of the ledger.

Worked example 2

You have a file of SQL called report.sql and a database called ledger.db. Run the file against the database, and also save the answer in a file called report.txt.

What we have: A file of SQL, a database file and the shell's redirections from T6.

What we need: One command that runs report.sql against ledger.db, and another that writes its answer into report.txt.

The plan: Feed the file in with <; send the answer out with >.

  1. To run it: sqlite3 ledger.db < report.sql. The < makes report.sql the input of sqlite3, as it made notes.txt the input of wc in T6.
  2. To save it: sqlite3 ledger.db < report.sql > report.txt. The > sends what sqlite3 prints into report.txt instead of the screen.
  3. Because report.txt is a file, not a terminal, sqlite3 writes plain lists there, with bars between the values.

sqlite3 ledger.db < report.sql runs the file; adding > report.txt saves the answer, as plain lists.

Check: Run cat report.txt afterwards. It shows lines such as boiler|96.5, the batch format, not boxes.

Another way: Add -box to keep the boxes in the file: sqlite3 -box ledger.db < report.sql > report.txt.

A path that fails: Writing sqlite3 ledger.db report.sql > report.txt on an older sqlite3. Since version 3.53, sqlite3 reads a file named on the command line when its name ends in .sql, but older versions take report.sql as a line of SQL, and it fails. The < works in every version.

When you are stuck: which way to run SQL

If sqlite3 seems to hang with no answer, it is waiting at its prompt for you to type: you gave it a file name and nothing else. Type .quit and press Enter, then give it the SQL in quotes or from a file.

If the answer has no boxes, the output is going somewhere other than your terminal, or your sqlite3 is older than 3.53. Add -box.

A common mistake

Putting a semicolon after a dot-command, or forgetting one after SQL. .tables needs none, because it is not SQL. SELECT * FROM gauges; needs one, because the engine only runs a statement once it has ended.

Your turn

Which command runs the SQL in a file called check.sql against the database city.db?Tap to reveal
  1. The database file comes first, right after sqlite3.
  2. The < feeds the file in.

sqlite3 city.db < check.sql

Change the first block above to print a table with ascii borders instead of a box, using an option.Tap to reveal
  1. The option for a table with + and - borders is -table.
  2. It goes before the database name.

sqlite3 -table ledger.db "SELECT name, reading FROM gauges;" draws the same rows with +, - and | borders.

Is .tables SQL? How can you tell?Tap to reveal
  1. Look at its first character.

No. It starts with a dot, so it is a dot-command for the sqlite3 program, and it needs no semicolon.

Did you know?

In the flight software of an airliner

SQLite's list of well-known users says that Airbus confirms SQLite is being used in the flight software for the A350 XWB family of aircraft. The same list admits that most users never say so: because SQLite is in the public domain, most developers use it in their projects without ever telling its authors.

Why it fits here: It answers the topic's question in part: a library small enough to carry inside any program is trusted even inside an airliner's flight software.

Source: SQLite: Well-Known Users of SQLite

Far more test code than code

SQLite is tested to an unusual depth. Its own page on testing says that, as of version 3.42.0, the library was about 155.8 thousand lines of C code, while the project had 590 times as much test code and test scripts. Its tests include out-of-memory tests, crash and power loss tests and fuzz tests.

Why it fits here: It finishes the topic's question: the engine inside so many programs is checked by hundreds of times more test code than it has code.

Source: SQLite: How SQLite Is Tested

Affidavits in a firesafe

SQLite has no licence to agree to. All of its code and documentation has been dedicated to the public domain. Every author, and representatives of the companies they work for, signed affidavits giving up their rights, and the signed originals are kept in a firesafe at the main offices of a company called Hwaci.

Why it fits here: It explains why SQLite can sit inside so many programs: anyone may copy and ship it, with nothing to sign.

Source: SQLite: SQLite Is Public Domain

In one line

SQLite keeps a whole database in one file; the sqlite3 command opens that file and runs SQL given in quotes, from a file or from a here-document, drawing boxes at a terminal and plain lists everywhere else.

Making a table: CREATE TABLE

At a glance

CREATE TABLE rules a new page: it names a table and every one of its columns.

Each column gets a name and a type, and may get a rule, such as NOT NULL. SQLite stores every value as one of five storage classes: INTEGER, REAL, TEXT, BLOB or NULL. A column's type is a hint called affinity, so a REAL column turns the text '4.2' into a number but keeps 'fast' as text. A STRICT table refuses values that do not fit. INTEGER PRIMARY KEY gives every row its own number.

Take a guess: Which kinds of value that most programming languages have does SQLite have no storage class for at all?

Before a database can hold a single gauge, it needs a table to put it in, as the Registrar ruled a page before anyone wrote on it. The statement that rules the page is CREATE TABLE. It names the table, and then names every column and says what kind of value each one holds.

Here is the statement that made the Ledger-keepers' gauges table. The file runs it, then asks sqlite3 three things: which tables exist, what statement made the gauges table, and what the table holds so far.

make.sql (ledger.db does not exist yet: sqlite3 makes it)

CREATE TABLE gauges (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  hall TEXT,
  unit TEXT,
  reading REAL
);
.tables
.schema gauges
SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < make.sql

gauges
CREATE TABLE gauges (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  hall TEXT,
  unit TEXT,
  reading REAL
);
╭────┬──────┬──────┬──────┬─────────╮
│ id │ name │ hall │ unit │ reading │
╘════╧══════╧══════╧══════╧═════════╛

Read the statement aloud, line by line. "Create a table called gauges, with these columns. A column called id, holding an integer, which is the primary key. A column called name, holding text, which may not be NULL. Columns called hall and unit, holding text. A column called reading, holding a real number."

Then read the answers. .tables printed gauges: the table exists. .schema gauges printed the CREATE TABLE statement back, exactly as it was written, line breaks and all: SQLite keeps it. The SELECT printed only the column names, in a box with a double line at its foot. The table is ruled, but no row has been written yet.

The parts of CREATE TABLE

PartIn the exampleWhat it means
CREATE TABLE and a nameCREATE TABLE gaugesMake a new table called gauges.
Brackets around the columns( ... );The list of columns, then the semicolon that ends the statement.
A column: a name, then a typehall TEXTA column called hall, meant for text.
A rule after the typename TEXT NOT NULLEvery row must have a name.
The row's own numberid INTEGER PRIMARY KEYA number for each row, which SQLite fills in for you.
Commas between columnsunit TEXT,Every column but the last ends with a comma.

The line breaks and spaces are only for people. SQLite would read the whole statement just as well on one line. Writing one column per line makes it easy to see each column and its type, so most people write it that way.

The five kinds of value

SQLite stores every value as one of five storage classes. A column's type says which of them it expects.

Storage classWhat it holdsExamplesA column type that asks for it
INTEGERA whole number6, 1200, -3INTEGER
REALA number with a decimal point96.5, 4.2, 2.0REAL
TEXTWords and characters, in quotes'boiler', 'Engine Hall'TEXT
BLOBRaw bytes, such as a picturex'ff00'BLOB
NULLNo value: not knownNULLAny column, unless it says NOT NULL

Here SQLite is unusually easy-going, and it is worth knowing how. A column's type is a strong hint, not a locked door. SQLite calls the hint the column's affinity. When a value can be turned into the column's kind without losing anything, SQLite turns it. When it cannot, SQLite keeps the value as it is.

query.sql (a fresh database)

CREATE TABLE readings (gauge TEXT, value REAL);
INSERT INTO readings VALUES ('boiler', 96);
INSERT INTO readings VALUES ('pump', '4.2');
INSERT INTO readings VALUES ('fan', 'fast');
INSERT INTO readings VALUES ('chimney', NULL);
SELECT gauge, value, typeof(value) FROM readings;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬───────┬───────────────╮
│  gauge  │ value │ typeof(value) │
╞═════════╪═══════╪═══════════════╡
│ boiler  │  96.0 │ real          │
│ pump    │   4.2 │ real          │
│ fan     │ fast  │ text          │
│ chimney │ NULL  │ null          │
╰─────────┴───────┴───────────────╯

The SQL function typeof() names the storage class of a value. Read its column from the top. The whole number 96 was stored as the real number 96.0, because the column holds REAL. The text '4.2' looked like a number, so it became the number 4.2. The text 'fast' could not become a number, so it stayed text. NULL stayed NULL.

Most databases would refuse 'fast' outright. PostgreSQL does, as T12 will show. SQLite can be asked to behave the same way: add the word STRICT after the closing bracket, and every value must fit its column's type.

query.sql (a fresh database)

CREATE TABLE readings (gauge TEXT, value REAL) STRICT;
INSERT INTO readings VALUES ('pump', '4.2');
INSERT INTO readings VALUES ('fan', 'fast');
SELECT gauge, value, typeof(value) FROM readings;

Terminal: sqlite3 ledger.db < query.sql

Error near line 3: cannot store TEXT value in REAL column readings.value
╭───────┬───────┬───────────────╮
│ gauge │ value │ typeof(value) │
╞═══════╪═══════╪═══════════════╡
│ pump  │   4.2 │ real          │
╰───────┴───────┴───────────────╯

The strict table still turned '4.2' into a number, because nothing was lost. It refused 'fast' with a clear message naming the table and the column. The rest of the file still ran: sqlite3 reports an error and goes on to the next statement.

The row's own number: INTEGER PRIMARY KEY

Every row of a table needs a way to be told apart from the others. Two gauges might one day share a name, but they can never share a number. A column declared INTEGER PRIMARY KEY holds that number. Leave it out when you add a row, and SQLite gives the row the next number: 1, then 2, then 3. The next section watches it happen.

A primary key is a column whose value names exactly one row. Lesson 05 uses these numbers to join two tables together, as the Registrar's folio numbers tie the pages of her ledger together.

Worked example 3

Write the CREATE TABLE statement for the city's halls: each hall has a name, which every hall must have, and the number of its Circle. Then add three halls and read them back.

What we have: Two facts per hall: its name, which is text and may not be missing, and its Circle, a whole number.

What we need: A CREATE TABLE statement with two columns, an INSERT and a SELECT.

The plan: Name the table for one row (a hall), choose a type for each fact, add NOT NULL where a value must exist.

  1. The table: CREATE TABLE halls (. A plural name is the custom: the table holds many halls.
  2. The name is text and must exist: name TEXT NOT NULL, with a comma, because another column follows.
  3. The Circle is a whole number: circle INTEGER, with no comma, because it is the last column, then );.
  4. The INSERT and SELECT come from the next sections; run them now to see the table work.

query.sql (a fresh database)

CREATE TABLE halls (
  name TEXT NOT NULL,
  circle INTEGER
);
INSERT INTO halls VALUES ('Engine Hall', 6), ('Clock Tower', 8), ('Archive', 7);
SELECT * FROM halls;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────┬────────╮
│    name     │ circle │
╞═════════════╪════════╡
│ Engine Hall │      6 │
│ Clock Tower │      8 │
│ Archive     │      7 │
╰─────────────┴────────╯

CREATE TABLE halls (name TEXT NOT NULL, circle INTEGER); makes the table, and the three halls come back with their Circles.

Check: The numbers in the circle column sit on the right of their boxes: sqlite3 lines numbers up on the right and text on the left. That tells you 6, 8 and 7 really are numbers.

Another way: Add an id column, id INTEGER PRIMARY KEY, as the gauges table has. Then every hall gets its own number, even if two halls are ever given the same name.

A path that fails: Writing circle INTEGER, with a comma after the last column. The engine then expects another column and finds a closing bracket instead, and reports a syntax error near the bracket.

Worked example 4

Ledger.db already has a gauges table. Run the CREATE TABLE statement for it again. What happens, and how can a file that must run every morning avoid the problem?

What we have: A table that exists already, and the same CREATE TABLE statement.

What we need: The error, read correctly, and a statement that is safe to run twice.

The plan: Run it once and read the message; then add IF NOT EXISTS.

  1. Running it again stops with a message, because a database cannot hold two tables with one name:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

CREATE TABLE gauges (id INTEGER PRIMARY KEY, name TEXT NOT NULL);

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: table gauges already exists
  CREATE TABLE gauges (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
               ^--- error here
  1. Read the message from left to right. A parse error means SQLite refused the statement while reading it, before running anything. Near line 1 says where in the file. The caret points at the table's name.
  2. Adding IF NOT EXISTS after CREATE TABLE tells SQLite to do nothing when the table is already there:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

CREATE TABLE IF NOT EXISTS gauges (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
.tables

Terminal: sqlite3 ledger.db < query.sql

gauges

The plain statement fails with "table gauges already exists"; with IF NOT EXISTS it does nothing and reports no error.

Check: Run the second file twice. It prints gauges both times and never an error, and the old table, with its five gauges, is untouched.

A path that fails: Expecting IF NOT EXISTS to change the table's columns. It does not compare anything: if a table of that name exists, the statement is skipped, even if its columns differ.

When you are stuck: CREATE TABLE errors

Read the message for the word near: SQLite names the word where it gave up. A syntax error near a closing bracket usually means a comma after the last column.

A comma missing between two columns is sneakier. In CREATE TABLE halls (name TEXT circle INTEGER); SQLite reads circle INTEGER as more words of name's type, makes a table with one column and says nothing. The trouble shows later, as "table halls has no column named circle".

Run .schema to see which tables exist and how they were made. If the table you meant is not there, check the file name you gave sqlite3.

A common mistake

Treating the column type as a lock. In an ordinary SQLite table, a REAL column can still hold text such as 'fast'. If a column must only hold its own kind, make the table STRICT.

Your turn

Write a CREATE TABLE statement for a table called couriers, with an id as the primary key, a name that may not be missing, and a speed as a real number.Tap to reveal
  1. One column per line, a comma after every column but the last.
  2. The id: id INTEGER PRIMARY KEY.

CREATE TABLE couriers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, speed REAL);

In a column declared REAL, what does typeof() say about the values 7, '7.5' and 'seven'?Tap to reveal
  1. Can each one become a real number without losing anything?

real (7 becomes 7.0), real ('7.5' becomes 7.5) and text ('seven' stays text).

Which dot-command shows the statement that made a table?Tap to reveal
  1. It shows the table's shape, its schema.

.schema, followed by the table's name if you want only that one.

Did you know?

No true and false, no dates

SQLite has no storage class for true and false. Its documentation says Boolean values are stored as the integers 0 and 1, and the keywords TRUE and FALSE, recognised since version 3.23.0, are only other spellings for 1 and 0. Nor is there a storage class for dates and times; they are kept as text, real numbers or integers.

Why it fits here: It answers the topic's question: two kinds that most languages have, true and false and dates, have no storage class of their own in SQLite.

Source: SQLite: Datatypes In SQLite

The engine that breaks the rule

SQLite's documentation says that every other SQL database engine, as far as its authors know, uses static, rigid typing, where a column decides a value's type. SQLite ties the type to the value instead. Some developers, it admits, are aghast at its flagrant rule-breaking, and for them it added STRICT tables in version 3.37.0, on 27 November 2021.

Why it fits here: It explains affinity and STRICT: SQLite's loose typing is its own choice, and STRICT came later for those who wanted the usual rules.

Sources: SQLite: Datatypes In SQLite; SQLite: STRICT Tables

In one line

CREATE TABLE names a table and each of its columns with a type (INTEGER, REAL, TEXT or BLOB) and any rules (NOT NULL, PRIMARY KEY); SQLite treats the type as a hint unless the table is STRICT.

Putting rows in: INSERT

At a glance

INSERT puts rows into a table: INSERT INTO a table, the columns to fill, then VALUES in the same order.

Text goes in single quotes, and an apostrophe inside it is written twice; numbers and NULL go bare. One INSERT can add many rows, each in its own brackets. A column that is left out gets NULL. A row that arrives without an id gets one more than the largest id in the table, so gaps can appear, and they are normal: an id names a row, it does not count rows.

Take a guess: What happens when a table's ids reach the largest number a computer can store in them?

A ruled page with no lines on it answers no questions. Rows go into a table with INSERT. Here is the first gauge going into the empty table from the last section, followed by a SELECT to see it.

query.sql (a fresh database: the file makes the table first)

CREATE TABLE gauges (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  hall TEXT,
  unit TEXT,
  reading REAL
);
INSERT INTO gauges (name, hall, unit, reading) VALUES ('boiler', 'Engine Hall', 'C', 96.5);
SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬────────┬─────────────┬──────┬─────────╮
│ id │  name  │    hall     │ unit │ reading │
╞════╪════════╪═════════════╪══════╪═════════╡
│  1 │ boiler │ Engine Hall │ C    │    96.5 │
╰────┴────────┴─────────────┴──────┴─────────╯

Read the INSERT aloud: "Insert into gauges, filling the columns name, hall, unit and reading, these values: boiler, Engine Hall, C and 96.5." The first pair of brackets names the columns; the second gives their values, in the same order. The first column named gets the first value, the second gets the second, and so on.

The id column was not named at all, yet the row came back with id 1. That is INTEGER PRIMARY KEY at work: a row that arrives without an id gets the next number.

Writing values

Kind of valueHow to write itExample
Textinside single quotes'Engine Hall'
Text with an apostrophethe apostrophe twice'Couriers'' Yard'
A whole numberas it is1200
A real numberwith a decimal point96.5
Nothing knownthe word NULL, with no quotesNULL

Single quotes mark text in SQL, always. Double quotes mean something else: they mark a name, such as a column's, as the mistakes section shows. And because a single quote ends the text, an apostrophe inside the text is written twice. SQLite stores 'Couriers'' Yard' as Couriers' Yard, with one apostrophe.

Many rows at once

One INSERT can add many rows: list each row's values in its own brackets, with commas between them. This file adds the other four gauges to the table that already holds the boiler. The chimney's INSERT leaves out the reading, so the chimney gets NULL there.

query.sql (ledger.db already holds the table and the boiler)

INSERT INTO gauges (name, hall, unit, reading) VALUES
  ('pump', 'Engine Hall', 'bar', 4.2),
  ('fan', 'Engine Hall', 'rpm', 1200);
INSERT INTO gauges (name, hall, unit) VALUES ('chimney', 'Couriers'' Yard', 'C');
INSERT INTO gauges (name, hall, unit, reading) VALUES ('pendulum', 'Clock Tower', 's', 2);
SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────────┬────────────────┬──────┬─────────╮
│ id │   name   │      hall      │ unit │ reading │
╞════╪══════════╪════════════════╪══════╪═════════╡
│  1 │ boiler   │ Engine Hall    │ C    │    96.5 │
│  2 │ pump     │ Engine Hall    │ bar  │     4.2 │
│  3 │ fan      │ Engine Hall    │ rpm  │  1200.0 │
│  4 │ chimney  │ Couriers' Yard │ C    │ NULL    │
│  5 │ pendulum │ Clock Tower    │ s    │     2.0 │
╰────┴──────────┴────────────────┴──────┴─────────╯

This is the full table that the rest of the track reads. Notice three things. The ids went on from 2 to 5, each new row taking the next number. The fan's 1200 came back as 1200.0, because the reading column holds REAL. And the chimney's reading is NULL, because its INSERT did not name that column. A column that is left out gets NULL, unless the table says otherwise.

How the ids are given

You may give an id yourself; SQLite then uses yours. A later row that comes without one gets one more than the largest id in the table, not one more than the last row added. Watch the bell and the lamp:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

INSERT INTO gauges (name, reading) VALUES ('clock', 12);
INSERT INTO gauges VALUES (10, 'bell', 'Clock Tower', 'Hz', 440);
INSERT INTO gauges (name) VALUES ('lamp');
SELECT id, name, reading FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────────┬─────────╮
│ id │   name   │ reading │
╞════╪══════════╪═════════╡
│  1 │ boiler   │    96.5 │
│  2 │ pump     │     4.2 │
│  3 │ fan      │  1200.0 │
│  4 │ chimney  │ NULL    │
│  5 │ pendulum │     2.0 │
│  6 │ clock    │    12.0 │
│ 10 │ bell     │   440.0 │
│ 11 │ lamp     │ NULL    │
╰────┴──────────┴─────────╯

The clock took 6, the next number. The bell was given 10 by hand. The lamp then took 11, one more than the largest id so far, and numbers 7 to 9 were never used. Gaps like these are normal. An id names a row; it does not count them.

The middle INSERT has no list of columns at all. That form must give a value for every column, in the order the CREATE TABLE statement listed them: id, name, hall, unit, reading. It is shorter, but it breaks as soon as someone adds a column to the table, so most people name the columns every time.

Worked example 5

Add a gauge called kettle to the Couriers' Yard. A first try printed an error. Find the mistake and fix it.

What we have: A table with name and hall columns, and a hall whose name has an apostrophe in it.

What we need: An INSERT that stores the hall's name with its apostrophe.

The plan: Run the first try, read where the error points, then write the apostrophe the SQL way.

  1. The first try wrote the apostrophe once:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

INSERT INTO gauges (name, hall) VALUES ('kettle', 'Couriers' Yard');
SELECT name, hall FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: near "Yard": syntax error
   gauges (name, hall) VALUES ('kettle', 'Couriers' Yard'); SELECT name, hall FR
                                      error here ---^
  1. The single quote after Couriers ended the text early. SQLite then met the word Yard where it expected a comma or a bracket, so it gave up near "Yard".
  2. Notice that the SELECT on the next line never ran. The unclosed quote after Yard swallowed it: everything up to the next quote counted as one long piece of text, so SQLite read both lines as one broken statement.
  3. Write the apostrophe twice: 'Couriers'' Yard'.

INSERT INTO gauges (name, hall) VALUES ('kettle', 'Couriers'' Yard'); stores the kettle in Couriers' Yard.

Check: Run the fixed file with the SELECT after it. The kettle comes back with the hall Couriers' Yard, one apostrophe, and the other gauges are still there.

Another way: Some programs use a hall name without an apostrophe to dodge the problem. That changes the data to suit the language; doubling the quote keeps the data right.

A path that fails: Putting the hall in double quotes, "Couriers' Yard". SQLite reads double quotes as a column's name and answers that there is no such column.

When you are stuck: INSERT errors

Count both lists. The column list and the values list must be the same length; SQLite says "1 values for 2 columns" when they are not.

Look at every piece of text: single quotes around it, and any apostrophe inside it written twice. A message about a word inside your text, such as near "Yard", means a quote closed too early.

A common mistake

Forgetting the quotes around text. VALUES (boiler, 96.5) makes SQLite look for a column called boiler, and it answers "no such column: boiler". Text always goes in single quotes; only numbers and NULL go bare.

Your turn

Write an INSERT that adds a gauge called gate to the Clock Tower, with no unit and no reading yet.Tap to reveal
  1. Name only the columns you have values for.
  2. The columns you leave out get NULL.

INSERT INTO gauges (name, hall) VALUES ('gate', 'Clock Tower');

The table's largest id is 11. A new row arrives without an id. Which id does it get?Tap to reveal
  1. SQLite looks at the largest id, not at how many rows there are.

12, one more than the largest id.

How do you store the text it's, with its apostrophe, in SQL?Tap to reveal
  1. A single quote ends the text, so the one inside is written twice.

'it''s'

Did you know?

When the ids run out

A row's id can grow very large: the largest it can be is 9223372036854775807. SQLite's documentation says what happens when the largest id in a table reaches that number. SQLite starts picking positive ids at random until it finds one that has not been used. Only if it cannot find one does the INSERT fail, with an SQLITE_FULL error.

Why it fits here: It answers the topic's question, and stretches the rule for new ids: one more than the largest works until the largest cannot grow.

Source: SQLite: SQLite Autoincrement

A doubled quote, as in Pascal

SQL's way of writing an apostrophe inside text comes from an older language. SQLite's documentation says a single quote within a string is written as two single quotes in a row, as in Pascal. The backslash escapes of C and JavaScript are not supported, because they are not standard SQL.

Why it fits here: It explains a rule of this topic: the doubled apostrophe in INSERT is SQL's standard way, borrowed from Pascal, not a quirk of SQLite.

Source: SQLite: SQL Language Expressions

Many rows in one INSERT

Adding many rows with one INSERT was not always possible in SQLite. Its list of changes records that version 3.7.11, released on 20 March 2012, enhanced the INSERT syntax to allow multiple rows to be inserted through the VALUES clause. Before that, each row needed an INSERT of its own.

Why it fits here: It dates a form this topic uses: one INSERT with several rows arrived in SQLite in 2012.

Source: SQLite: Release History

In one line

INSERT INTO a table, naming the columns, then VALUES in the same order: text in single quotes (an apostrophe written twice), numbers and NULL bare; left-out columns get NULL, and a left-out id gets one more than the largest.

Reading a table: SELECT

At a glance

SELECT reads rows out of a table and hands them back as a new table, the answer.

The star means every column, in the table's order; a list of names gives just those, in your order. SELECT never changes the table. Keywords and names may be written in any case, and two dashes start a comment. The rows usually come back in the order of their ids, but SQL promises no order at all unless the query asks for one with ORDER BY.

Take a guess: If no order is promised, how could a programmer find out that a program wrongly depends on one?

You have met SELECT in every section so far. Now look at it closely, because it is the statement you will write most often. It reads rows out of a table and hands them back as a new table, the answer.

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT * FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────┬──────────┬────────────────┬──────┬─────────╮
│ id │   name   │      hall      │ unit │ reading │
╞════╪══════════╪════════════════╪══════╪═════════╡
│  1 │ boiler   │ Engine Hall    │ C    │    96.5 │
│  2 │ pump     │ Engine Hall    │ bar  │     4.2 │
│  3 │ fan      │ Engine Hall    │ rpm  │  1200.0 │
│  4 │ chimney  │ Couriers' Yard │ C    │ NULL    │
│  5 │ pendulum │ Clock Tower    │ s    │     2.0 │
╰────┴──────────┴────────────────┴──────┴─────────╯

Read it aloud: "Select every column from gauges." The star, *, means every column, in the order the table was made. FROM names the table to read. With nothing else, SELECT returns every row.

Choosing columns

Name the columns you want, with commas between them, and the answer holds only those, in your order. The star gave id first because the table lists it first; a list of names puts them where you put them:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT reading, name FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬──────────╮
│ reading │   name   │
╞═════════╪══════════╡
│    96.5 │ boiler   │
│     4.2 │ pump     │
│  1200.0 │ fan      │
│ NULL    │ chimney  │
│     2.0 │ pendulum │
╰─────────┴──────────╯

Choosing columns does not change the table. SELECT only reads; the gauges table still has five columns and five rows. You asked a narrower question, and the answer is a narrower table.

Capital letters and comments

SQL does not care whether its keywords are in capitals, and SQLite does not care about the case of table and column names either. select works as well as SELECT, and GAUGES finds the gauges table. The custom of writing keywords in capitals is for people: it makes SQL's own words stand out from your names.

Two dashes, --, start a comment: SQLite ignores everything from there to the end of the line. Use comments to say what a query is for.

query.sql (ledger.db already holds the gauges table of the create and insert sections)

-- every gauge and the hall it stands in
select NAME, hall from GAUGES;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬────────────────╮
│   name   │      hall      │
╞══════════╪════════════════╡
│ boiler   │ Engine Hall    │
│ pump     │ Engine Hall    │
│ fan      │ Engine Hall    │
│ chimney  │ Couriers' Yard │
│ pendulum │ Clock Tower    │
╰──────────┴────────────────╯

The answer's titles say name and hall, in small letters, as the table spelt them, even though the query wrote NAME. The comment line did nothing at all.

The order of the rows

So far the rows have always come back in the order of their ids. That is what SQLite usually does when nothing else is asked for, but SQL makes no promise about it. A different database, or the same one after many changes, may hand the rows back in another order.

When the order matters, say so. Lesson 03 adds ORDER BY, which sorts the answer. Until then, read an answer as a set of rows, not as a list in a fixed order.

Worked example 6

A clerk wants a list of every gauge's name and unit, and nothing else. Write the query, run it, and check it.

What we have: The gauges table in ledger.db, with columns id, name, hall, unit and reading.

What we need: An answer with two columns, name then unit, and one row for each gauge.

The plan: SELECT the two columns by name, FROM the gauges table.

  1. The columns, in the order the clerk wants: SELECT name, unit.
  2. The table: FROM gauges, then the semicolon.

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT name, unit FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬──────╮
│   name   │ unit │
╞══════════╪══════╡
│ boiler   │ C    │
│ pump     │ bar  │
│ fan      │ rpm  │
│ chimney  │ C    │
│ pendulum │ s    │
╰──────────┴──────╯

SELECT name, unit FROM gauges; gives five rows, each a name and its unit.

Check: Count the rows: five, one per gauge, as SELECT * gave. Count the columns: two. The chimney is there with its unit, C, even though its reading is NULL, because the query never asked for the reading.

Another way: SELECT * would also show the names and units, but with three columns the clerk did not want. Asking for exactly the columns you need keeps answers easy to read.

A path that fails: Writing SELECT name unit FROM gauges; without the comma. SQLite reads unit as a new title for the name column, so the answer has one column, titled unit, full of names. Lesson 02 meets this kind of title on purpose, with the word AS.

Worked example 7

The Registrar ran a query and got an error instead of a table. Read the error and fix the query.

What we have: A query with a misspelt column name.

What we need: The same question, answered.

The plan: Run it, read the message and its caret, then correct the word it points at.

  1. The first try:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT nme FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: no such column: nme
  SELECT nme FROM gauges;
         ^--- error here
  1. The message names the problem, no such column: nme, and the caret under the statement points at the word.
  2. The table has no column called nme; it has name. Fix the spelling: SELECT name FROM gauges;.

SELECT name FROM gauges; lists the five names.

Check: Run the fixed query: five names, boiler to pendulum, and no error. If you are not sure of a column's spelling, .schema gauges lists every column.

A path that fails: Guessing at spellings one after another. One look at .schema gives the exact names, and saves many runs.

When you are stuck: SELECT

If SQLite says no such column, run .schema and copy the column's name from it. If it says no such table, check both the table's name and the database file's name: a wrong file holds no tables at all.

If an answer has the right rows but in an unexpected order, nothing is wrong yet: without ORDER BY, the order is not promised.

A common mistake

Thinking that SELECT changes the table. It only reads. Choosing two columns gives an answer with two columns; the table keeps all five.

Your turn

Write a query that lists every gauge's hall, then its name.Tap to reveal
  1. Columns come out in the order you list them.

SELECT hall, name FROM gauges;

Does select * from Gauges; work on the gauges table?Tap to reveal
  1. Think about keywords, and about table names.

Yes. SQLite ignores the case of keywords and of table names.

What does a line that starts with -- do in a file of SQL?Tap to reveal
  1. It is for the people who read the file.

Nothing: it is a comment, and SQLite ignores the rest of the line.

Did you know?

A switch that turns answers around

SQLite has a setting for catching programs that trust an order nobody promised. With PRAGMA reverse_unordered_selects turned on, many SELECT statements without an ORDER BY return their rows in the reverse of their usual order. The documentation says this can help debug applications that make invalid assumptions about the result order.

Why it fits here: It answers the topic's question: flip the order on purpose, and a program that depends on it breaks where you can see it.

Source: SQLite: Pragma statements

Titles over an empty answer

The column titles that sqlite3 now prints over an answer with no rows are newer than they look. SQLite's list of changes records that in version 3.54.0, released on 9 October 2026, the command's columnar output modes began to show the column name header by default even if the query returns no rows.

Why it fits here: It explains what an empty SELECT shows: the titles over no rows are a 3.54 change, so older sqlite3 versions may print nothing.

Source: SQLite: Release History

In one line

SELECT reads a table: * for every column, or a list of names in your own order, FROM the table's name; it never changes the table, and the order of rows is not promised without ORDER BY.

Where it is used

Databases are everywhere data is kept, which is nearly everywhere. Three places matter for this track.

SQLite, inside other programs

SQLite rarely shows itself. It is a small library that programs carry inside them, so you use it without knowing. SQLite's own website lists every Android phone, every iPhone, every Mac, every Windows 10 and 11 computer, and the Firefox, Chrome and Safari browsers among the places it is found. Firefox, for one, keeps its list of the pages you have visited in an SQLite file.

Apps use it to keep what they need on the device itself: messages to send later, settings, a cache of what was last downloaded. Because the whole database is one file, an app can carry it, copy it or back it up like any other file.

Database servers, behind websites

A website with many visitors keeps its data on a database server, such as PostgreSQL or MySQL, which many programs can reach at once over a network. The SQL is nearly the same: SELECT, INSERT and CREATE TABLE work there as they do here. T12 moves the Ledger-keepers' tables onto PostgreSQL, and the full-stack app of the later steps keeps its data there.

Asking questions of data

People who study data, from shop owners to scientists, keep it in tables and ask questions in SQL: how many orders came from Pune last month, which product sells best on Sundays. A spreadsheet can answer a few such questions by hand; SQL answers them in one statement, over millions of rows.

WhereWhich databaseWho reaches it
A phone app or a browserSQLite, in a file on the deviceOne program, the app itself
A website's serverPostgreSQL or MySQLMany programs at once, over the network
A report or an analysisEither, or a data warehousePeople writing SQL

Mistakes and how to find them

SQLite's error messages are short, exact and worth reading slowly. Every one of them says three things: what kind of error it is, where it happened and what went wrong. This file holds six broken statements, one per line, each a mistake that beginners make. sqlite3 reports each one and goes on to the next.

query.sql (ledger.db already holds the gauges table of the create and insert sections)

INSERT INTO gauges (name, reading) VALUES ("kettle", 3.5);
INSERT INTO gauges (name, reading) VALUES (kettle, 3.5);
INSERT INTO gauges (name, reading) VALUES ('kettle');
INSERT INTO gauges (reading) VALUES (3.5);
INSRT INTO gauges (name) VALUES ('kettle');
INSERT INTO gauges (id, name) VALUES (1, 'kettle');

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: no such column: "kettle" - should this be a string literal in single-quotes?
  INSERT INTO gauges (name, reading) VALUES ("kettle", 3.5);
                               error here ---^
Parse error near line 2: no such column: kettle
  INSERT INTO gauges (name, reading) VALUES (kettle, 3.5);
                               error here ---^
Parse error near line 3: 1 values for 2 columns
Error near line 4: NOT NULL constraint failed: gauges.name
Parse error near line 5: near "INSRT": syntax error
  INSRT INTO gauges (name) VALUES ('kettle');
  ^--- error here
Error near line 6: UNIQUE constraint failed: gauges.id

Reading a message

Take the first message apart. Parse error means SQLite refused the statement while reading it, before running anything; nothing in the table changed. Near line 1 is the line of the file where the statement starts. After the colon comes what went wrong. Below it, sqlite3 copies the statement and points at the trouble: the caret, ^, with "error here".

The message for line 4 starts with plain Error instead. That statement was read without trouble, and it failed while running, because it broke one of the table's rules. Parse errors are mistakes in the writing; plain errors are rules the data broke.

The messageWhat went wrongThe fix
no such column: "kettle" - should this be a string literal in single-quotes?Text in double quotes, which mark names in SQL.'kettle'
no such column: kettleText with no quotes, read as a column's name.'kettle'
1 values for 2 columnsFewer values than columns named.Give a value for every column named, or name fewer columns.
NOT NULL constraint failed: gauges.nameA row without a value that the table requires.Give the row a name.
near "INSRT": syntax errorA misspelt keyword.INSERT
UNIQUE constraint failed: gauges.idAn id that another row already has.Leave the id out, and SQLite picks the next one.

The missing semicolon

A semicolon ends each statement. Leave one out between two statements, and SQLite reads them as one long statement, which makes no sense:

query.sql (a fresh database)

SELECT 'one'
SELECT 'two';

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: near "SELECT": syntax error
  SELECT 'one' SELECT 'two';
               ^--- error here

The caret points at the second SELECT, where the first statement should have ended. Neither statement ran. Notice that sqlite3 printed the two lines as one: that is how it read them.

The last statement of a file is the exception. When the file ends, sqlite3 runs whatever is left, semicolon or not:

query.sql (ledger.db already holds the gauges table of the create and insert sections)

SELECT name FROM gauges;
SELECT name, reading FROM gauges WHERE id = 1

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ boiler   │
│ pump     │
│ fan      │
│ chimney  │
│ pendulum │
╰──────────╯
╭────────┬─────────╮
│  name  │ reading │
╞════════╪═════════╡
│ boiler │    96.5 │
╰────────┴─────────╯

Do not lean on that. At sqlite3's own prompt, a statement without a semicolon is not finished: sqlite3 waits for the rest of it, and nothing happens until you type the semicolon. End every statement with one, always.

The misspelt file name

This one surprises everybody once. Give sqlite3 a database file that does not exist, and it does not complain: it makes a new, empty database with that name. The first sign of trouble is a query that finds no tables.

Terminal (ledger.db already holds the gauges table)

sqlite3 ledgr.db "SELECT name FROM gauges;"
ls
Parse error in 2nd command line argument: no such table: gauges
ledger.db  ledgr.db

The file was meant to be ledger.db, but the command said ledgr.db. sqlite3 made ledgr.db, empty, so the gauges table was "missing". The message names the place too: the statement was the 2nd argument on the command line, counting sqlite3 itself as the 0th. If a table you know exists is suddenly missing, check the file's name first, then delete the stray empty file.

A way to debug

  1. Read the first word: a parse error is in your writing, a plain error is in your data or a rule.
  2. Read the line number and the caret, and look exactly there.
  3. Check quotes: single for text, apostrophes doubled, double only for names.
  4. Check commas and semicolons: between columns, between rows, after every statement.
  5. Check names against .schema, and the database file's own name against ls.

When you are stuck: an error you do not understand

Shrink the file. Run the failing statement alone; if it still fails, take parts away until it works, then put them back one at a time. The last part you put back holds the mistake.

Copy the message's words exactly, with the quotes, and search the SQLite documentation for them.

A common mistake

Fixing the first error and expecting the rest to vanish. sqlite3 reports each failing statement separately, and a file with three mistakes prints three messages. Fix them in order, and run the file again after each fix.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

To do thisWrite this
Run SQL from the terminalsqlite3 ledger.db "SELECT * FROM gauges;"
Run a file of SQLsqlite3 ledger.db < query.sql
Make a tableCREATE TABLE gauges (id INTEGER PRIMARY KEY, name TEXT NOT NULL, reading REAL);
Make it only if it is missingCREATE TABLE IF NOT EXISTS gauges (...);
Add a rowINSERT INTO gauges (name, reading) VALUES ('boiler', 96.5);
Add several rowsINSERT INTO gauges (name) VALUES ('pump'), ('fan');
Read every columnSELECT * FROM gauges;
Read some columnsSELECT name, reading FROM gauges;
Text with an apostrophe'Couriers'' Yard'
See a value's kindSELECT typeof(reading) FROM gauges;
List the tables.tables
See how a table was made.schema gauges
Choose the drawingsqlite3 -box ..., -table, -list -header, -csv, -json

Words to know: database, table, row, column, value, NULL, statement, keyword, SQLite, sqlite3, dot-command, storage class, affinity, STRICT, primary key, parse error.

Self-check

Say each answer aloud before you open it.

What is the difference between a row and a column?Tap to reveal
  1. Think of one line of a ledger, and one heading of it.

A row is one record, going across; a column is one named fact that every row fills in, going down.

Which three ways can sqlite3 take its SQL, besides typing at its prompt?Tap to reveal
  1. Quotes, a file, a here-document.

In quotes after the file name, from a file with <, and from a here-document.

Which quotes mark text in SQL, and how is an apostrophe written inside text?Tap to reveal
  1. Double quotes mark something else.

Single quotes; an apostrophe inside is written twice, as in 'Couriers'' Yard'.

A REAL column of an ordinary table is given the text '7'. What does it store?Tap to reveal
  1. Can '7' become a number without losing anything?

The real number 7.0.

What is the difference between a parse error and a plain error?Tap to reveal
  1. One happens while reading, one while running.

A parse error is a statement SQLite could not read; a plain error is a statement that broke a rule while running.

The story: The first ruled page

By evening a single ruled page lies on the long table. Across its top run the column names: id, name, hall, unit and reading. Under them each gauge has one line, and every line has the same columns in the same order. Where a reading is missing, the box is left empty on purpose.

A clerk asks to see every gauge, and the page answers at once, in a neat table. Another asks for the chimney's line alone, and the ledger finds it without anyone turning a sheet.

The Registrar writes the page's title in the index at the front of the ledger. "One table, kept in one book," she says. "Tomorrow we ask it sharper questions."

Reagents gathered: table, row, column, CREATE TABLE, INSERT, SELECT.

Sources