Lesson 1: Databases and tables
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
Topic: What a database is · history, people
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
Topic: What a database is · history, people
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
Topic: SQLite and the sqlite3 command · real-world, tools
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
Topic: SQLite and the sqlite3 command · tools, numbers
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
Topic: SQLite and the sqlite3 command · law, history
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
Topic: Making a table: CREATE TABLE · tools
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
Topic: Making a table: CREATE TABLE · history, tools
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
Topic: Putting rows in: INSERT · numbers, tools
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
Topic: Putting rows in: INSERT · history, languages
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
Topic: Putting rows in: INSERT · history, tools
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
Topic: Reading a table: SELECT · tools
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
Topic: Reading a table: SELECT · tools, history
Lesson 2: SELECT and filtering
The remainder throws fractions away first
SQLite's % operator works only with whole numbers. Its documentation says % casts both of its operands to INTEGER first, and then computes the remainder after dividing the left integer by the right one. So 7.5 % 2 is worked out from 7 and 2, and sqlite3 prints 1.0, not 1.5.
Why it fits here: It answers the topic's question and stretches its arithmetic: % drops the fraction before it divides.
Source: SQLite: SQL Language Expressions
Topic: Choosing and computing columns · tools, numbers
DISTINCT keeps one NULL
When SELECT DISTINCT meets several NULLs, it keeps just one, as if they were equal, though NULL equals nothing. SQLite's page on NULLs says it was changed to do this, making NULLs indistinct for SELECT DISTINCT, to match other engines, and admits that this seems somewhat arbitrary.
Why it fits here: It shows a corner of DISTINCT from this topic: repeated NULLs count as one row, by a choice made for compatibility.
Source: SQLite: NULL Handling in SQLite Versus Other Database Engines
Topic: Choosing and computing columns · tools, history
Two ways to say not equal
PostgreSQL's documentation says that <> is the standard SQL notation for not equal, and that != is only an alias, converted to <> at a very early stage of parsing. SQLite's documentation lists both too, and adds a second equals: in SQLite, equals can be either = or ==.
Why it fits here: It answers the topic's question: <> is the standard not-equal, and != is a friendlier spelling that databases accept.
Sources: PostgreSQL: Comparison Functions and Operators; SQLite: SQL Language Expressions
Topic: Keeping the rows that fit: WHERE · languages, tools
Capitals come before small letters
When SQLite compares two pieces of text, it uses a collating function, and every column's is BINARY unless the table says otherwise. BINARY compares text with memcmp(), byte by byte. In those bytes every capital letter comes before every small one, so to SQLite 'Z' is less than 'a', and a test such as name < 'b' keeps every name that starts with a capital.
Why it fits here: It explains why text tests are exact about capitals: SQLite compares the bytes, and a capital's byte differs from a small letter's.
Source: SQLite: Datatypes In SQLite
Topic: Keeping the rows that fit: WHERE · tools
What counts as true
A WHERE test does not have to be a comparison. SQLite turns whatever the test gives into a number: zero is false, NULL stays NULL, and every other value is true. Its documentation lists the surprises: the text 'english' and the text '0' both count as false, while '1english' counts as true, because it turns into the number 1.
Why it fits here: It shows how this topic's tests are judged: every result becomes a number, and only non-zero numbers keep a row.
Source: SQLite: SQL Language Expressions
Topic: Combining tests: AND, OR and NOT · tools
When not known is good enough
AND and OR can sometimes answer even with a NULL inside. SQLite's documentation says that, when paired with NULL, AND gives false if the other test is false, and OR gives true if the other test is true. One false is enough to sink an AND, and one true to float an OR, whatever the unknown side holds.
Why it fits here: It joins this topic to NULL: AND and OR still give a firm answer when the known side settles it.
Source: SQLite: SQL Language Expressions
Topic: Combining tests: AND, OR and NOT · tools
Only English letters fold
SQLite's LIKE ignores capitals only for the letters of ASCII, the basic English alphabet. Its documentation gives the example that 'a' LIKE 'A' is true, but 'æ' LIKE 'Æ' is false, because SQLite understands upper and lower case only for ASCII characters by default. Accented letters, such as the ä of German, keep their case.
Why it fits here: It answers the topic's question: LIKE's case rule covers English letters only, so other alphabets match exactly.
Source: SQLite: SQL Language Expressions
Topic: Ranges, lists and patterns: BETWEEN, IN and LIKE · languages, tools
A pattern with bash's wildcards
SQLite has a second pattern test for people who know the shell. GLOB works like LIKE but, in the words of its documentation, uses the Unix file globbing syntax for its wildcards: the * and ? of bash. GLOB is also case sensitive, unlike LIKE. So name GLOB 'p*' finds pump and pendulum, while GLOB 'P*' finds nothing.
Why it fits here: It extends this topic's patterns: GLOB matches with the shell's * and ?, and cares about capitals.
Source: SQLite: SQL Language Expressions
Topic: Ranges, lists and patterns: BETWEEN, IN and LIKE · tools
Decided by experiment
SQLite's page on NULLs says the SQL standards seemed ambiguous about how to handle them. So popular SQL engines were tested instead, with a script run by volunteers in May 2002. SQLite had first been written to answer yes to every question in the chart. None of the other engines worked that way, so SQLite was changed to work like Oracle, PostgreSQL and DB2.
Why it fits here: It answers the topic's question: NULL's rules in SQLite came from testing other engines, because the standards were unclear.
Source: SQLite: NULL Handling in SQLite Versus Other Database Engines
Topic: Finding missing values: IS NULL · history, tools
A test that never says not known
IS is more than a way to find NULL. SQLite's documentation says IS and IS NOT work like = and != except when one or both sides are NULL. Two NULLs are IS-equal, and a NULL and a value are not. An IS or IS NOT test can never give NULL, so reading IS 4.2 always gives a firm answer.
Why it fits here: It widens this topic's IS NULL: IS compares any two values without ever answering not known.
Source: SQLite: SQL Language Expressions
Topic: Finding missing values: IS NULL · tools
Lesson 3: Sorting and limiting
A sort builds an index of its own
When no index already holds the rows in the order asked for, SQLite sorts by building a temporary one. Its documentation says it stores each row in a transient index whose key is the ORDER BY terms. When the query has run, SQLite walks that index from beginning to end and hands the rows back in the desired order.
Why it fits here: It answers the topic's question: a sort is a temporary index, keyed on the ORDER BY terms, read from start to end.
Source: SQLite: Temporary Files Used By SQLite
Topic: Sorting with ORDER BY · tools
How ORDER BY reads a word in quotes
SQLite reads each ORDER BY term by fixed rules. A name that matches an alias of the answer's columns sorts by that column. Any other expression, its documentation says, is evaluated, and the value it gives is used to order the rows. So ORDER BY 'reading', in single quotes, is a piece of text, the same for every row, and the rows do not move.
Why it fits here: It explains the quiet mistake of this topic's lesson: a quoted name is evaluated as text, so every row gets the same sort value.
Source: SQLite: SELECT
Topic: Sorting with ORDER BY · tools
Columns counted from 1
SQLite accepts ORDER BY 2, 1. Its documentation says a constant whole number K in ORDER BY is taken as the K-th column of the answer, with the columns numbered from left to right starting with 1. A JavaScript array counts its places from 0, so ORDER BY 1 is the first column, not the second.
Why it fits here: It explains this topic's ORDER BY 2, 1: a number names a column of the answer, counted from 1.
Source: SQLite: SELECT
Topic: Several columns, and settling ties · tools, numbers
Keeping the ties: WITH TIES
PostgreSQL can cut an answer short without splitting a tie. Its documentation says the WITH TIES option of FETCH FIRST returns any additional rows that tie for the last place, according to the ORDER BY clause, which is then required. Asked for the top three readings, it would also keep a fourth gauge tied with the third.
Why it fits here: It answers the topic's question: ties can be kept whole when an answer is cut, with the standard's WITH TIES.
Source: PostgreSQL: SELECT
Topic: Several columns, and settling ties · tools, languages
Smallest here, largest there
Two well-known databases sort NULL at opposite ends. SQLite's documentation says it considers NULL values to be smaller than any other values for sorting. PostgreSQL's says its null values sort as if larger than any non-null value, so NULLS FIRST is its default for DESC order and NULLS LAST otherwise.
Why it fits here: It shows why this topic says to write NULLS FIRST or NULLS LAST: the defaults of the two databases are opposites.
Sources: SQLite: SELECT; PostgreSQL: Sorting Rows (ORDER BY)
Topic: Where NULL goes when you sort · tools
NULLS LAST arrived in 2019
SQLite has not always understood NULLS FIRST and NULLS LAST. Its list of changes puts them in version 3.30.0, released on 2019-10-04, in a line that reads: add support for the NULLS FIRST and NULLS LAST syntax in ORDER BY clauses. So a query that must run on an older SQLite sorts its NULLs with the IS NULL key instead.
Why it fits here: It answers the topic's question, and explains why older queries use the IS NULL key in place of NULLS LAST.
Source: SQLite: Release History
Topic: Where NULL goes when you sort · history, tools
Offset first, on purpose
SQLite's documentation admits that its comma form of LIMIT is counter-intuitive: with the comma, the first number is the offset and the second the limit, the reverse of LIMIT with OFFSET. It calls the reversal intentional, because it maximizes compatibility with other SQL database systems, whose queries can then run unchanged.
Why it fits here: It answers the topic's question: the comma form copies other databases, and SQLite kept it knowing it confuses.
Source: SQLite: SELECT
Topic: Only the first few: LIMIT and OFFSET · tools, history
LIMIT is not in the standard
The word most people learn for cutting an answer short is not standard SQL. PostgreSQL's documentation calls LIMIT and OFFSET PostgreSQL-specific syntax, also used by MySQL. It says the SQL:2008 standard brought in its own clauses for the same job, OFFSET with FETCH FIRST, which IBM's DB2 also uses.
Why it fits here: It places this topic's LIMIT among databases: common and convenient, but not the standard's own spelling.
Source: PostgreSQL: SELECT
Topic: Only the first few: LIMIT and OFFSET · languages, history
The skipped rows still cost work
OFFSET does not jump straight to page 5000. PostgreSQL's documentation warns that the rows skipped by an OFFSET clause still have to be computed inside the server, so a large OFFSET might be inefficient. To show rows 1,00,001 to 1,00,020, the database first works out the 1,00,000 rows before them.
Why it fits here: It shows the cost behind this topic's pages: every skipped row is still found and sorted.
Source: PostgreSQL: LIMIT and OFFSET
Topic: Only the first few: LIMIT and OFFSET · tools, numbers
iif(): a CASE written short
SQLite has a shorter way to write a two-way choice: iif(test, yes, no). Its documentation says iif() is really a short-hand notation for a CASE expression, and generates the same bytecode as CASE WHEN X THEN Y ELSE Z END. It arrived in version 3.32.0, on 2020-05-22, and a later version also allowed the spelling if().
Why it fits here: It answers the topic's question: iif() is a CASE written short, the same work inside.
Sources: SQLite: Built-In Scalar SQL Functions; SQLite: Release History
Topic: Rules of your own: CASE · tools, history
The short form compares with =
The short form, CASE unit WHEN 'C', is an = test inside. SQLite's documentation says the same NULL-handling rules apply as for an = operator, so a NULL base value never matches a WHEN: it always gets the ELSE, or NULL when there is none. The one difference it names between the two forms: the short form works out the value only once.
Why it fits here: It explains this topic's short form: it is an = test inside, which is why it can never match NULL.
Source: SQLite: SQL Language Expressions
Topic: Rules of your own: CASE · tools
Lesson 4: Aggregates and grouping
Two counts in one pass: FILTER
An aggregate in SQLite can take a FILTER clause. Its documentation says that if a FILTER clause is provided, only the rows for which its test is true are included in the aggregate. So COUNT(*) FILTER (WHERE reading > 100) counts the 2 hot gauges, while a plain COUNT(*) beside it in the same SELECT still counts all 8.
Why it fits here: It answers the topic's question: a FILTER clause lets one aggregate count some rows while another counts all.
Source: SQLite: Built-in Aggregate Functions
Topic: Counting: COUNT · tools
DISTINCT works inside other aggregates too
DISTINCT is not only for COUNT. SQLite's documentation says that in any aggregate function that takes a single argument, the argument can be preceded by DISTINCT, and duplicate elements are filtered before they reach the function. SUM(DISTINCT reading) adds the pump's and the valve's 4.2 only once, and gives 1830.7 in place of 1834.9.
Why it fits here: It widens this topic's COUNT(DISTINCT): any one-argument aggregate can drop repeats first, sometimes by mistake.
Source: SQLite: Built-in Aggregate Functions
Topic: Counting: COUNT · tools, numbers
A sum of nothing is NULL, by the standard
SQLite's documentation admits that NULL is not normally a helpful result for the sum of no rows. But the SQL standard requires it, and most other engines do it, so SQLite's sum() does the same, to be compatible. Its own total() is offered as a convenient way around this design problem: with no rows, sum() returns NULL and total() returns 0.0.
Why it fits here: It explains this topic's NULL from SUM: the standard asks for it, and total() exists to avoid it.
Source: SQLite: Built-in Aggregate Functions
Topic: Adding up: SUM, AVG and ROUND · tools, history
Negative places: two databases, two answers
SQLite's documentation says that if ROUND's second argument is omitted or negative, it is taken to be 0, so ROUND(1234.567, -2) gives 1235.0. PostgreSQL rounds to the left of the point instead: its documentation gives round(1234.56, -1) as 1230. Both break a tie the same way, though: PostgreSQL says ties are broken by rounding away from zero.
Why it fits here: It answers the topic's question, and shows that a function with the same name can differ between databases.
Sources: SQLite: Built-In Scalar SQL Functions; PostgreSQL: Mathematical Functions and Operators
Topic: Adding up: SUM, AVG and ROUND · tools, numbers
A sum too big to hold
A whole number in SQLite has a largest value, and SUM can run past it. Its documentation says sum() throws an integer overflow exception if all its inputs are whole numbers or NULL and the total overflows at any point. SQLite's total() never throws that error, because its result is always a floating point value; it gives up a little exactness instead.
Why it fits here: It shows a limit behind this topic's SUM of whole numbers, and another difference between sum() and total().
Source: SQLite: Built-in Aggregate Functions
Topic: Adding up: SUM, AVG and ROUND · tools, numbers
SQLite's bare columns
A column in an aggregate query that is neither grouped nor inside an aggregate is called a bare column. SQLite's documentation says you usually do not know which input row such a column comes from. With exactly one min() or max() in the query, though, every bare column takes its value from a row that holds that minimum or maximum. That is why SELECT name, MAX(reading) names the fan.
Why it fits here: It answers the topic's question: beside a single MIN or MAX, a bare column comes from the row holding that value.
Source: SQLite: SELECT
Topic: Smallest and largest: MIN and MAX · tools
One name, two functions
SQLite's documentation notes that max() is a simple function when it has two or more arguments, and an aggregate when it has only one. The two treat NULL differently. MAX(reading) skips the chimney's NULL, but the many-argument max() returns NULL if any of its arguments is NULL, so max(2, NULL) is NULL.
Why it fits here: It sharpens this topic's two kinds of max: one looks down a column and skips NULL, the other looks along a row and does not.
Source: SQLite: Built-In Scalar SQL Functions
Topic: Smallest and largest: MIN and MAX · tools
PostgreSQL's rule, and its exception
PostgreSQL turns SQLite's quiet guess into an error. Its documentation says that in a grouped table, columns not listed in GROUP BY cannot be referenced except in aggregate expressions. There is one exception: if the group is the table's primary key, other columns of that table are functionally dependent on it, since each key has exactly one row, and so they may be shown.
Why it fits here: It sets this topic's rule beside a real database that enforces it, with the sensible exception it allows.
Source: PostgreSQL: Table Expressions
Topic: One answer per group: GROUP BY · tools
Subtotals and a grand total: ROLLUP
PostgreSQL can give several levels of totals in one query. ROLLUP(e1, e2, ...) groups by the whole list and by every shorter beginning of it, ending with the empty list, which is one group of everything. Its documentation says this is commonly used for hierarchical data, such as total salary by department, by division and company-wide.
Why it fits here: It answers the topic's question: with ROLLUP, one query gives each group's total and the grand total too.
Source: PostgreSQL: Table Expressions
Topic: One answer per group: GROUP BY · tools
HAVING without GROUP BY, since 2022
SQLite once allowed HAVING only beside GROUP BY. Its list of changes says the HAVING clause is now allowed on any aggregate query, even one with no GROUP BY clause, in the release built on 2022-06-25. That is why HAVING placed before GROUP BY fails at the GROUP: SQLite reads the HAVING as a test of the whole table first.
Why it fits here: It answers the topic's question, and explains the error that HAVING before GROUP BY gives in this lesson.
Source: SQLite: Release History
Topic: Choosing groups: HAVING · tools, history
No nicknames in PostgreSQL's HAVING
SQLite lets HAVING use a name given with AS, such as HAVING n > 2. PostgreSQL's documentation says an output column's name can be used in ORDER BY and GROUP BY, but not in WHERE or HAVING; there the expression must be written out. HAVING COUNT(*) > 2 works in both.
Why it fits here: It shows why this topic writes the aggregate out in HAVING: the short name is SQLite's own convenience.
Source: PostgreSQL: SELECT
Topic: Choosing groups: HAVING · tools
SQLite moves row tests out of HAVING
A test on a grouped column, such as HAVING hall = 'Engine Hall', is really about rows. SQLite spots this by itself. Its list of changes says it transfers any terms of the HAVING clause that use only columns mentioned in GROUP BY over to the WHERE clause, for faster processing, so fewer rows are grouped at all.
Why it fits here: It shows the WHERE and HAVING split of this topic from the inside: the database moves row tests to WHERE itself.
Source: SQLite: Release History
Topic: Choosing groups: HAVING · tools
Lesson 5: Joins
Checks you must switch on
SQLite has understood foreign keys for a long time. Its documentation describes the support for foreign key constraints introduced in version 3.6.19, on 2009-10-14. Yet the checks are disabled by default, for compatibility with older programs, and a program must switch them on with PRAGMA foreign_keys for every connection it opens.
Why it fits here: It answers the topic's question, and explains why this lesson's lamp with hall 9 was accepted until the checks were switched on.
Source: SQLite: Foreign Key Support
Topic: Two tables, and the keys between them · tools, history
Parent and child tables
SQLite's documentation names the two sides of a link. The parent table is the table that the foreign key refers to: here, halls. The child table holds the REFERENCES clause: here, gauges. It admits that some books call the parent the referenced table, which is arguably more correct, but tends to lead to confusion.
Why it fits here: It gives this topic's two tables the names the documentation uses: halls is the parent, gauges the child.
Source: SQLite: Foreign Key Support
Topic: Two tables, and the keys between them · tools, languages
A join is a loop inside a loop
SQLite's documentation says it implements joins as nested loops. By default the left-most table in FROM forms the outer loop and the right-most the inner one. But SQLite will nest the loops in a different order when that helps it choose better indexes, which is why the order you write an inner join in does not change its answer.
Why it fits here: It shows what this topic's JOIN does underneath: for each row of one table, a search through the other.
Source: SQLite: The SQLite Query Optimizer Overview
Topic: Side by side: JOIN · tools
At most 64 tables in one join
SQLite does not support joins of more than 64 tables. Its documentation explains why: the planner keeps track of the tables in a join with bitmaps, one bit per table. It also says the planner is efficient enough that even a large join can be prepared quickly, and the limit cannot be raised.
Why it fits here: It answers the topic's question with SQLite's real limit, and the reason behind the number.
Source: SQLite: Limits In SQLite
Topic: Side by side: JOIN · tools, numbers
RIGHT and FULL joins, long overdue
For most of its life SQLite had LEFT JOIN but no RIGHT JOIN or FULL JOIN. Its list of changes for version 3.39.0, released on 2022-06-25, opens with the words: add (long overdue) support for RIGHT and FULL OUTER JOIN. A query that keeps both loose ends, as this lesson's FULL JOIN does, needed a workaround before then.
Why it fits here: It answers the topic's question with the release that brought them, and SQLite's own admission that they were late.
Source: SQLite: Release History
Topic: Keeping the unmatched: LEFT JOIN · tools, history
Outer joins keep their order
SQLite's planner may reorder the tables of an inner join freely, because the answer is the same either way. Its documentation says outer joins are different: they are neither commutative nor associative, and hence are never reordered. That is the topic's rule seen from the inside: in a LEFT JOIN, which table comes first changes the answer.
Why it fits here: It explains why swapping the tables of this topic's LEFT JOIN kept the Archive and lost the compass.
Source: SQLite: The SQLite Query Optimizer Overview
Topic: Keeping the unmatched: LEFT JOIN · tools, numbers
Named after Descartes
Every pairing of the rows of two tables is called their Cartesian product. PostgreSQL's documentation uses the name, and gives the size rule: if the tables have N and M rows, the joined table has N * M rows. The name honours René Descartes: the idea came from his way of naming points by coordinates, a pair of numbers.
Why it fits here: It answers the topic's question, and ties the cross join to the grid of coordinates met in school maths.
Sources: PostgreSQL: Table Expressions; Wikipedia: Cartesian product; Wolfram MathWorld: Cartesian Product
Topic: Every pairing: CROSS JOIN · history, numbers
CROSS JOIN as a steering wheel
In SQLite, writing CROSS JOIN does more than say every pairing. Its documentation says SQLite treats the CROSS JOIN operator specially, and never reorders the tables in it. That gives a programmer a way to force the order of the nested loops. It helps when SQLite's own choice turns out to be slow.
Why it fits here: It shows an extra job of this topic's CROSS JOIN in SQLite: fixing the order in which the tables are looped over.
Source: SQLite: The SQLite Query Optimizer Overview
Topic: Every pairing: CROSS JOIN · tools
INTERSECT and EXCEPT
UNION has two siblings. SQLite's documentation says INTERSECT returns the rows that both answers share, and EXCEPT returns the rows of the left answer that the right one does not have. Like UNION, both remove duplicate rows. So the units used in both the Engine Hall and the Couriers' Yard are one INTERSECT away.
Why it fits here: It answers the topic's question: two answers of the same shape can also be intersected or subtracted.
Source: SQLite: SELECT
Topic: Stacking answers: UNION · tools, numbers
500 answers in one stack
A chain of SELECTs joined by UNION, UNION ALL, EXCEPT or INTERSECT is called a compound SELECT, and each SELECT in it a term. SQLite's documentation says the maximum number of terms is set by SQLITE_MAX_COMPOUND_SELECT, which defaults to 500, because such chains are built by a recursive algorithm and the limit keeps its stack small.
Why it fits here: It puts a number on this topic's stacking: one statement can hold up to 500 stacked SELECTs in SQLite.
Source: SQLite: Limits In SQLite
Topic: Stacking answers: UNION · tools, numbers
Lesson 6: Creating, updating and deleting
AUTOINCREMENT is usually not needed
Many tutorials add the word AUTOINCREMENT to an id column. SQLite's own documentation advises against it: the keyword imposes extra CPU, memory, disk space and disk I/O overhead and should be avoided if not strictly needed, and it is usually not needed. A plain INTEGER PRIMARY KEY already numbers new rows by itself, as this lesson's lamp showed.
Why it fits here: It saves a common habit from this topic's INSERT: the id fills itself without AUTOINCREMENT.
Source: SQLite: Autoincrement
Topic: Adding rows: INSERT · tools
RETURNING arrived in 2021
RETURNING is newer than most of SQLite. Its list of changes adds support for the RETURNING clause on DELETE, INSERT and UPDATE statements in version 3.35.0, released on 2021-03-12. Its documentation says the clause makes the statement return one result row for each row deleted, inserted or updated.
Why it fits here: It dates this topic's RETURNING, which older tutorials do not show.
Sources: SQLite: Release History; SQLite: The RETURNING Clause
Topic: Adding rows: INSERT · tools, history
A NULL passes a CHECK
SQLite's documentation spells out the CHECK rule. The test's result is turned into a number: if it is zero, the row breaks the rule; if it is NULL, or any other non-zero value, it does not. CHECK rules are also verified only when the table is written, never when it is read, so rows stored before a rule existed are not checked again.
Why it fits here: It explains this topic's icebox and chimney: a test on NULL is not zero, so the CHECK lets them through.
Source: SQLite: CREATE TABLE
Topic: Rules the table enforces: constraints · tools
A primary key that allows NULL
By the SQL standard, a primary key is never NULL. SQLite's documentation admits that, due to a bug in some early versions, this is not the case in SQLite: most primary key columns accept NULL, unless the column is an INTEGER PRIMARY KEY or declared NOT NULL. It could be fixed, but doing so might break legacy applications, so the quirk is documented instead.
Why it fits here: It answers the topic's question, and shows why this lesson's id is an INTEGER PRIMARY KEY.
Source: SQLite: CREATE TABLE
Topic: Rules the table enforces: constraints · tools, history
UPDATE FROM, borrowed from PostgreSQL
An UPDATE can take its new values from another table. SQLite's list of changes adds support for UPDATE FROM, following the PostgreSQL syntax, in version 3.33.0, released on 2020-08-14. With it, the gauges could take new readings from a table of fresh readings in one statement, matched row by row like a join.
Why it fits here: It answers the topic's question, and joins this lesson's UPDATE to lesson 05's joins.
Source: SQLite: Release History
Topic: Changing rows: UPDATE · tools, history
The count is a function too
The .changes on of this topic has an SQL twin. SQLite's documentation says the changes() function returns the number of rows changed, inserted or deleted by the most recently completed INSERT, DELETE or UPDATE statement. So SELECT changes(); right after an UPDATE tells a program how many rows its WHERE really matched.
Why it fits here: It gives this topic's safety check a form that works inside any program, not only in the sqlite3 shell.
Source: SQLite: Built-In Scalar SQL Functions
Topic: Changing rows: UPDATE · tools
Deleted, but not wiped
Deleting a row does not erase it from the file. SQLite's documentation says deleted content is usually not erased, but its space is marked as available for reuse, which can allow it to be recovered by a hacker or by forensic analysis. Running VACUUM cleans the database of all traces of deleted content, and PRAGMA secure_delete is another way.
Why it fits here: It answers the topic's question: a deleted row can linger in the file until VACUUM or secure_delete clears it.
Source: SQLite: VACUUM
Topic: Removing rows: DELETE · tools
The truncate shortcut
Emptying a whole table is fast in SQLite. Its documentation says that when a DELETE has no WHERE and no RETURNING, and the table has no triggers, it uses an optimization to erase the entire table content without visiting each row. This truncate optimization makes the delete run much faster, which is one more reason a missing WHERE can do its damage in an instant.
Why it fits here: It shows what this topic's DELETE without WHERE does inside: the whole table is cleared at once.
Source: SQLite: DELETE
Topic: Removing rows: DELETE · tools
Four changes, and only four
SQLite's documentation says it supports a limited subset of ALTER TABLE: a table can be renamed, and a column can be renamed, added or dropped. The reason is how it stores a table's shape: as the original text of the CREATE statement, which ALTER TABLE edits. Any other change, such as a new rule on an old column, means building a new table and copying the rows across.
Why it fits here: It explains the edges of this topic's ALTER TABLE: four changes, made by editing the stored CREATE text.
Source: SQLite: ALTER TABLE
Topic: Changing the table itself: ALTER and DROP · tools
Rename in 2018, drop in 2021
Two of this topic's statements are recent. SQLite's list of changes adds support for renaming columns within a table, with ALTER TABLE RENAME COLUMN, in version 3.25.0 of 2018-09-15. It adds support for ALTER TABLE DROP COLUMN in version 3.35.0 of 2021-03-12, the same release that brought RETURNING. Before then, both needed a new table and a copy.
Why it fits here: It answers the topic's question with the releases that made renaming and dropping a column possible.
Source: SQLite: Release History
Topic: Changing the table itself: ALTER and DROP · tools, history
Lesson 7: Subqueries
The first row, or NULL
SQLite's documentation says the value of a subquery used as a value is the first row of the inner query's result, and NULL if the inner query returns no rows. So a subquery that finds nothing does not fail: it hands the outer query a NULL, and any comparison with it is not known.
Why it fits here: It answers the topic's question: no rows gives NULL, and several rows give the first.
Source: SQLite: SQL Language Expressions
Topic: A question inside a question · tools
PostgreSQL says no
Where SQLite quietly takes the first row, PostgreSQL stops. Its documentation says it is an error to use a query that returns more than one row or more than one column as a scalar subquery. Like SQLite, it lets a subquery that returns no rows through, and takes the result to be null.
Why it fits here: It shows two databases parting ways on this topic's first-row rule, which is why IN is the safe choice for a list.
Source: PostgreSQL: Value Expressions
Topic: A question inside a question · tools
The NOT IN rule, in writing
The trap of this topic is the standard's own rule, not a bug. PostgreSQL's documentation states it. When no value on the right is equal and at least one right-hand row is null, NOT IN gives null, not true. It adds that this follows SQL's normal rules for combining nulls, the same rules lesson 02 met with AND and OR.
Why it fits here: It shows that the NOT IN trap is the SQL standard at work, the same in PostgreSQL as in SQLite.
Source: PostgreSQL: Subquery Expressions
Topic: A list from a query: IN · tools
An empty list is allowed in SQLite
SQLite lets the list after IN or NOT IN be empty, as in x IN (), and the test is then false for IN. Its documentation notes that most other engines require at least one element. So does the SQL92 standard. Generated queries, built by a program from a list that turns out empty, benefit most.
Why it fits here: It answers the topic's question: SQLite accepts an empty IN list, while the standard and most engines do not.
Source: SQLite: SQL Language Expressions
Topic: A list from a query: IN · tools, languages
Only 0 or 1
SQLite's documentation says the EXISTS operator always evaluates to one of the integer values 0 and 1: 1 if the inner query would return one or more rows, 0 if it would return none. It never gives NULL, which is exactly why NOT EXISTS keeps working where NOT IN breaks.
Why it fits here: It answers the topic's question: EXISTS is always 0 or 1, never NULL.
Source: SQLite: SQL Language Expressions
Topic: Is there any? EXISTS · tools, numbers
SELECT 1 or SELECT *, it does not matter
The habit of writing SELECT 1 inside EXISTS has a reason in the documentation. SQLite's says that the number of columns the inner query returns, and the values in them, have no effect on the result of EXISTS. It adds that rows containing NULL values are not handled any differently from rows without them.
Why it fits here: It explains this topic's SELECT 1: EXISTS reads whether a row exists, never what it holds.
Source: SQLite: SQL Language Expressions
Topic: Is there any? EXISTS · tools
Once, or every time
SQLite's documentation draws the line exactly. A subquery that refers to columns of the outer query is known as a correlated subquery, and it is reevaluated each time its result is required. An uncorrelated subquery is evaluated only once, and its result is reused as necessary, so the average of the whole works is worked out a single time.
Why it fits here: It answers the topic's question, and gives the reason a correlated subquery can be slow.
Source: SQLite: SQL Language Expressions
Topic: A subquery that looks outward · tools
Outer values held still
PostgreSQL's documentation explains how a subquery sees the outer row. It says the subquery can refer to variables from the surrounding query, and these act as constants during any one evaluation of the subquery. So for the fan, g.hall_id is just 1 while the inner average is worked out. For the bell it is 2.
Why it fits here: It shows what the link of this topic's correlated subquery means: the outer value is fixed during each inner run.
Source: PostgreSQL: Value Expressions
Topic: A subquery that looks outward · tools
WITH arrived in 2014
Named subqueries are a younger part of SQLite than SELECT. Its list of changes adds support for common table expressions and the WITH clause in version 3.8.3, released on 2014-02-03. Before then, every step of a long question had to be nested inside the next, in brackets within brackets.
Why it fits here: It dates this topic's WITH, the tool that lets a long query read in named steps.
Source: SQLite: Release History
Topic: Queries built on queries: FROM and WITH · tools, history
A Sudoku solved by one query
SQLite's page on WITH ends with what it calls outlandish recursive query examples. One computes an approximation of the Mandelbrot Set and prints it as ASCII-art, a picture made of characters. The next solves a Sudoku puzzle, read from an 81-character string with a full stop for each blank square, all with WITH RECURSIVE.
Why it fits here: It answers the topic's question, and shows how far this topic's starting row and repeated step can reach.
Source: SQLite: The WITH Clause
Topic: Queries built on queries: FROM and WITH · tools, numbers
No fact matches. Try a shorter word, or take the tag off.