Yellow marks are automatic key passages. They aren’t personal saved highlights. Select a timestamp to follow along with the video.
SQL is a programming language rather than only a query language, and a database engine pairs a compiler that turns each statement into procedures with a virtual machine that runs them. Indexes determine how efficiently those procedures reach the data: a binary search through an index replaces a full table scan, and multicolumn or covering indexes can satisfy both WHERE and ORDER BY clauses with less work. Engines differ in their internals, as SQLite uses bytecode and a layered design of B-trees, a pager and an OS layer built for small devices, while OR conditions are handled by merging row IDs through unions, intersections or bitmaps. The discussion closes with a rule for index design, which places WHERE terms before ORDER BY terms, a warning that extra indexes give the optimizer more chances to choose badly, and a note that SQLite plans to add bitmap indexes for larger systems.
Introduction and Goals of the Talk
With 85 slides to cover in 45 minutes, the talk starts punctually. The task is to explain how SQL database engines work in general, which is daunting for Richard, who knows only SQLite, the engine he wrote. About the other engines he is largely guessing, based on advice from other developers in the room.
The target audience is people who use SQL in their daily work and have done so for years. In Richard's experience giving talks, many people know a great deal about SQL, yet the database engine itself remains a black box. They know they need to create indices but do not really understand what indices do or why they matter, and many do not even realize that SQL is a programming language. The talk goes over these concepts, and even for those who already know the material, some of the diagrams may offer a new way of looking at things and help them use SQL better. Experts in the room are invited to correct any mistakes. With so many slides, the pace will be like drinking from a fire hose.
SQL as a Programming Language: Compiler and Virtual Machine
SQL is usually called a query language, but it is really a programming language, and a peculiar one. Instead of describing how something is to be done, as in C, the programmer states what is wanted and the compiler works out how to do it.
A SQL database engine therefore consists of two parts: a compiler that takes a SQL statement and compiles it into procedures, and a virtual machine underneath that runs those procedures. A simple query such as selecting everything from table one might be translated into a program that opens the database file containing the table, rewinds to the beginning, loops through the file reading out columns and returning them to the user until the end of the file is reached, and then closes the file.
That looks simple enough to write by hand in a few lines of C, and for this case it is. The usefulness of SQL appears with more complex queries, where perhaps a few thousand ways of implementing the query exist. Writing several thousand lines of C to do it manually is unattractive, as is worrying about all the different algorithms that might be employed, only to discover close to delivery that a different algorithm is needed and spend a couple of weeks redoing the work. SQL does this automatically: a few lines of SQL generate a large amount of procedural code, and simply adding an index to the schema selects a completely different set of algorithms. Choosing which algorithm accesses the data is the job of the query optimizer, which is where the voodoo happens.
The Engine Pipeline: Prepared Statements and Bytecode
SQL statements go into a compiler, which compiles them into procedures and produces a prepared statement. The prepared statement is really a computer program in a kind of virtual language. It is sent to the execution engine, which performs the actual querying and returns the results.
The front half, the compiler, uses the same techniques developed in the 1970s and well documented in the Dragon book; nothing new is going on there. In the middle, the prepared statement is the program that will run. In Richard's understanding, all the database engines represented by developers in the room, except SQLite, use a structure in C, or a tree of structures, as the prepared statement. SQLite instead generates bytecode, which more closely resembles what is found in Java, UCSD Pascal p-code or Parrot. A listing of this bytecode, something like assembly language, can be obtained with EXPLAIN, but the idea behind all of these approaches is the same.
A Firebird developer clarifies that the tree of structures applies to Firebird, Falcon and Nimbus, while MySQL uses what was described as a forest of goto flags. Richard also recalls a database engine that once generated native x86 machine code. That was unusual: it buys nothing in speed and causes portability problems.
SQLite Architecture and Storage Layers
The SQLite architecture diagram has three components at the top, which are simply the Dragon book compiler and equivalent to the earlier diagram. The bottom part is what runs the program. Because SQLite uses bytecode, its virtual machine is a big loop with a switch statement that switches on the opcodes and runs them in turn. Most other engines use a structure or tree of structures that their virtual machine walks, though this varies from place to place.
Beneath the virtual machine is the layer that does the database access. SQLite uses only B-trees, since it is supposed to be small. Most of the bigger engines offer B-trees, hash tables, R-trees and other schemes, often with a selection of options. For now, the assumption is B-trees, and the same principles apply. B-trees are well documented by Knuth, in volume three of his series on sorting and searching (formerly volume two).
Below that is a layer handling the cache and atomic commit, called the pager, and SQLite also has an OS portability layer because it must run on unusual platforms such as iPods and cell phones, where the operating system is not Unix. In MySQL, the bottom three layers, the B-tree, the pager and the OS layer, form the assembly that is plugged in and out when a different back end is used, and there are around 55 of those. In PostgreSQL there is the B-tree engine, hashing, R-tree and perhaps others. Firebird, as one of its developers confirms, uses 100% B-tree for everything.
Tables on Disk and Row IDs
Creating a table in SQL generally produces something on disk that looks approximately like this: a table with three columns, whose data is stored in the database file, plus a unique key on every row. SQLite calls this key the row ID. PostgreSQL calls it a ctid, and Firebird calls it a record number, or RDB DB key. SQLite exposes the row ID, so it can always be used and even set. In SQLite the row IDs are numbered sequentially, 1, 2, 3, 4, 5, although the example uses nonsequential numbers to suggest that the key might be a file offset used to find the record. Details vary from system to system, but the concept is generally always present.
The key, on the left, must be unique; the data, on the right, need not be.
In Firebird, the row ID can be used in a query, since it is set by the system, but it is not guaranteed to be stable across transactions: it can be reused if the record is deleted. It is also much more complicated than an offset in the file, being a two-level index.
Full Table Scans, Row ID Lookups and the Need for Indices
To find the price of peaches, one approach is to start at the beginning of the table and loop through record by record, looking for rows where the fruit column equals Peach, then pull the unit price from the matching row. That is a full table scan. With only seven entries it is fine; with seven entries, anything is plenty fast. With 700 million entries it takes far longer and does not work well.
A faster way, at least in SQLite, is to query by row ID: select the unit price from the table where the row ID equals 93. SQLite performs a binary search to find the row, which is very quick regardless of how many rows there are. On engines that use a file offset, there is not even a binary search; the engine seeks immediately to the row.
But nobody really cares what the unit price is for row 93. An end user wants the unit price for peaches. That requires an index. An index typically looks like a separate table, stored in a separate file, that holds all the values of the indexed column, here the fruit column, in order, and also records each value's row ID. The key point to remember is that there is a one-to-one mapping between entries in the index and in the main table and the
Index structure and row IDs
The thing being indexed becomes the first column of the index table, and an extra column holds the row ID. The combination of the indexed value and the row ID must be unique, which is never a problem because the row ID is always unique.
Looking up a value through an index
To get the unit price where fruit is equal to Peach, a binary search finds the entry in the index where fruit is Peach. That entry gives the row ID, and the row ID is then used to look into the main table to find the unit price. This is the basic idea behind indexing.
Indexes with multiple terms in the WHERE clause
Indexing also works when the WHERE clause has several terms. Suppose the goal is to find the unit price of California oranges. The first term, fruit equals orange, can use the index on fruit: a binary search for Orange in the index turns up two entries. Each of their row IDs is then used to look into the main table. The first, row ID zero, shows that the place grown in is Florida, which does not match, so that path is rejected. The second is California, so the result can be output. This is how a lookup works with two terms in the WHERE clause.
There might also be a second index, say index two, on the grown-in column. It works just like index one, except that it is sorted on grown-in instead of fruit. The same query could use it to look up the two entries for California in the grown-in index, but once again two entries come out and one of them fails when the main table is consulted, so only one result survives. This suggests creating an index with two columns.
Multicolumn indexes
A multicolumn index contains the two named columns in the order they were named. Sorting is primarily by the first column, and ties are broken by the second column. In the sample data the only tie is on oranges, where California comes first. (The slide labeling this index as index three contains an error.)
To find the unit price for California oranges, a binary search on the two-column index finds the one entry where both terms match. Its row ID is used to look into the main table, and the unit price is pulled from there. This is a little faster than the single-column approaches.
Four ways to answer one query
So far there are four ways to get the answer to that one query, with a few more to come. A full table scan works well on a seven-entry table but is a little slow on a 700-million-entry table. A single-column index on one term of the WHERE clause works acceptably, but some rows are still pulled in and checked, and fail because the other term did not match. A single-column index on the other term has the same weakness. A two-column index on both terms gets straight to the answer, and is generally a little faster.
Three-column covering indexes
A three-column index might cover fruit, grown-in and unit price. As before, the index is built by copying the values of the individual fields into the index in sorted order, following the order in which the columns were declared. For the query on California oranges, the binary search finds the entry, and no additional lookup in the main table is needed, because the data is already in the index and can be output straight away.
Visibility information and MVCC
This does not work for PostgreSQL, as covered in the previous talk in the same room, because PostgreSQL keeps visibility information in the main table. Whether a row is visible is unknown without a lookup in the main table. If visibility information were put in the index, as with heavy indexes, PostgreSQL could do this too.
Firebird, like PostgreSQL, and the Falcon engine in MySQL are similar to current PostgreSQL in this respect, while Firebird's Maria variant has heavy indexes by default. As the speaker understands it, Falcon does not do this because its indexes are prefix indexes that do not contain a complete copy of the actual data. Another participant points out that the indexes are prefix-compressed and the original data can still be reconstructed, and that the real issue is the MVCC information, which has to be fetched.
Using only some columns of a wide index
Wide indexes are still worth thinking about. Not every column in the index has to be used. To get the unit price for oranges alone, only the first term is needed. (The slide, made before coffee, contains a mistake: it should pull out two rows instead of one, but the idea is clear.)
It is also possible to select on the first column while a later column in the index does additional pruning.
Filtering inside the index
Only the fruit-equals-orange term is used for the lookup, which requires scanning two entries. Filtering on unit price can be done right there in the index, without the additional lookup into the main table. PostgreSQL will do this very thing, according to Bruce, because rejecting the California oranges that are too expensive needs no MVCC information, which eliminates one trip to the main table. Whether Firebird does this is disputed among the experts, and the speaker plans to check what it actually does.
Searching and sorting
Firebird, the internal Falcon engine and maybe MySQL in the future have another way of handling this type of query, which comes up as number six. Searching and sorting have a lot in common, as the title of Knuth's volume, Searching and Sorting, suggests. Indexes can come into play for sorting too.
For a query such as select star from table ordered by fruit, one approach is to walk through the entire table, pull out all the records and run them through a sorter. The sorter has to store copies of everything it sorts. In the speaker's world of SQLite, running on cell phones and iPods, sorters use a lot of memory and those devices have little of it, so this is a serious problem worth avoiding.
Ordering by row ID is easy: the query engine knows the rows come out in row ID order by themselves and does not need a sorter. That runs in linear time rather than N log N. Ordering by row ID decreasing is the same, starting at the end of the table and moving backward.
Ordering with an index
Nobody really cares about ordering by row ID; the useful order is by fruit. The index on fruit can be used: start at the beginning of the index, march down through it pulling out row IDs, and look up each row in the main table. Everything comes out in sorted order without a temporary table to store the results. It takes about the same amount of time but uses far less memory. On big iron that does not matter, but on a cell phone it is a huge win. A decreasing order works the same way, starting at the end of the index and moving toward the beginning.
Sorting with a covering index
If an index contains all the terms and the sort is by the first column of that index, the process becomes simple: start at the beginning of the index and work forward, knowing everything appears sorted by fruit, pulling out values and sending them to the user. In an MVCC system without heavy indexes, a visit to the main table is still needed to check visibility information; with heavy indexes that information is already in the index. This is a very fast way of getting an ORDER BY.
Which ORDER BY clauses an index supports
The same index serves ORDER BY decreasing, and ordering by the first two terms or the first three terms of the index, whether ascending or decreasing. All of this works well. It does not work, however, if the first term is ordered decreasing and the second ascending, or the reverse. The index can be declared to accommodate this: when creating an index, the descending and ascending keywords can be put after each term.
Index Direction and Column Order
The index must match the sort direction of the query. If the index is declared with the first term descending and the second ascending, an ORDER BY that uses that same pattern can use the index. If both terms are ascending, which is the default, the same query fails because the rows would appear out of order. Skipping a column also breaks the ordering. If a query orders by fruit and unit price while the grown-in column sits between them in the index, the results won't come out in the right order, so the index can't be used for the sort alone and one of the earlier ORDER BY techniques is needed. Additionally, an index can only be used to sort by its leftmost term. A query that sorts by a middle term can't rely on the index for ordering.
Constraints That Make Ordering Work
Some restrictions still allow the index to provide ordering. Consider a query that selects oranges and sorts by the state where they were grown. Grown-in is the second column of the index, so the index can't sort by it directly. However, the query constrains the leftmost column to a single value, fruit equals orange. Because the leftmost column is fixed, the rows already come out in the correct order for the grown-in column, and no sorting step is needed.
A General Rule for Designing Indexes
When creating an index to serve a query, start with the WHERE clause terms, which go first in the index, and follow them with the ORDER BY terms. The WHERE and ORDER BY terms may overlap, but there can be no gaps, meaning no extra column between them. The result set terms should also be included in the index. These can have gaps or overlaps without causing a problem, as long as they all appear somewhere in the index. In the SQLite developer's experience, this question comes up about once a week on the SQLite mailing list, so the rule may also help users of other database engines.
Using Only the First Key Part in MySQL
An audience member asks whether MySQL behaves differently when a query uses only the first key part of a multi-column index. Pretty much every database engine works the same way in this situation, so the behavior described for the first key part applies there as well.
OR Clauses and Full Table Scans
Queries with OR in the WHERE clause are a different case. Earlier examples used only AND. A full table scan always produces the correct result, such as when asking for the unit price of everything that is orange or grown in California. However, a full scan is always slow, so it's usually avoided. The typical approach is to create a separate index on fruit and another on grown-in. The engine looks up all California entries in the grown-in index and collects their row IDs. It then looks up all orange entries in the fruit index and collects their row IDs. This produces two sets of row IDs, which are combined with a union to get the final set of row IDs. In the example, the union yields three distinct row IDs, and those are used to fetch the desired rows from the table.
Merging Row IDs from Single-Column Indexes
There are several ways to combine these row IDs. With single-column indexes, the row IDs come out of each index in sorted order. This means the union can be computed as a streaming merge, always taking the smallest remaining row ID next. The merge requires no temporary storage, which makes it a good fit for devices with little memory, such as cell phones. However, if the index has two columns, such as a two-column index on fruit, the row IDs no longer come out in the right order, so they must be sorted before the merge can happen.
Bitmap Indexes and Firebird's Approach
A common alternative is a bitmap index. The engine searches each index, sets a bit in a bit mask for every entry that matches, and may compress the result. This produces one bitmap per index. The bitmaps are then combined with OR, and the engine walks the resulting bitmap to retrieve the matching table entries in order. Firebird creates two bitmaps and then merges them. PostgreSQL reportedly works logically in a similar way, but it creates a single bitmap and modifies it according to the second index. The underlying idea is the same.
Combining Index Results with Intersections
The same approach can handle an intersection instead of a union. For the ongoing example, the query looks up all California entries in one index and all orange entries in another, then selects the entries they have in common. In this case, that is entry 204, which gives the result immediately. This is the sixth method for solving the example query. It works well, but it requires more work than a two-column index, and far more work than a covering index, which can answer the query without going to the table at all.
Trade-Offs and Complex WHERE Clauses
The advantage of this approach is that it doesn't need multi-column indexes. A smaller set of indexes can still deliver reasonable performance, though not peak performance. It also supports unusual WHERE clauses with arbitrary Boolean expressions. For example, a query might ask for the unit price of California oranges together with anything grown in North Carolina. A tree of intersections and unions over bitmap indexes can retrieve the desired data for these kinds of expressions.
Key Takeaways for Index Design
SQL is a programming language, with a compiler and a virtual machine behind it. Indexes are not magic, and they have to make sense for the query. On the SQLite mailing list, people often report that they created many indexes but their queries are still slow, and the answer usually lies in the query itself, which still has to match the indexes. The talk also recommends avoiding too many indexes in a schema. Even a simple query had six different execution methods, and that count excludes joins and subqueries, which were cut from the talk. As joins and other features are added, the number of ways to solve a problem grows rapidly. More indexes give the optimizer more choices and more chances to make a mistake, so indexes should be kept to a minimum. The talk has moved quickly, about 28 minutes in, and roughly ten minutes remain for questions.
Why Firebird Favors Bitmaps
An audience member asks about Firebird's approach. Firebird scans the index to collect record numbers, which are dense, and sets them in a bitmap. There are three main reasons it works this way. First, combining results with AND and OR works very well with bitmaps. Second, disk access is far slower than memory, and sequential disk reads are fast. Because bitmap order matches physical order, Firebird avoids random access. Third, the approach greatly simplifies the optimizer. It can use every index available without choosing among them, since it can combine them all with AND and OR. The audience member summarizes that Firebird prefers this method because it is simple to plan. The response confirms that on server hardware it should be just as fast, since data streams off the disk in sequential order, which beats random access.
The Real Cost of Sorting
The talk stresses that people overestimate the cost of sorting. In the SQLite developer's view, sorting is cheap. On server hardware, a system can sort a huge number of records in the time it takes to perform one disk access. Phones don't have disks in the same sense, but even on a device with a disk, sorting a million records is workable. Using sorting to avoid disk access is therefore a good trade.
Can the Planner Be Tricked into Using an Index?
An audience member asks whether the planner can be tricked into using the first column by writing a condition such as fruit equals fruit, or fruit not equal to banana. It can't. The sorting trick discussed earlier still applies, but a condition like fruit in orange or grape means the first column is no longer guaranteed to come out in the right order. The engine therefore sorts the results manually up front. It might get lucky, but there's no guarantee.
Index Preference in SQLite
Asked whether SQLite prefers complex indexes or many small ones, the answer is that SQLite prefers larger indexes. As of now, SQLite doesn't use bitmap indexing, though that is being added. Consequently, a WHERE clause containing an OR currently causes a full table scan. This is one of the constraints of fitting into 256 kilobytes, but the developer expects it to be remedied by spring, after which SQLite will use the full bitmap approach. For now, the existing approach is preferred, and it will likely remain faster for SQLite because the engine targets lower-end hardware, where memory is a major factor.
Power Use and Mobile Constraints
After the keynote, the developer told Brian that concerns about wasting power are never a problem with SQLite, because the cell phone and
Battery life over CPU and memory
iPod users keep telling the developers that they don't care about CPU time or memory use. What matters to them is how quickly the battery runs down, so any change that saves battery power is a plus.
A serverless design with clear tradeoffs
A common question is how SQLite differs from MySQL. MySQL runs as a server, while SQLite has no server. It runs only when an application uses it and reads and writes the disk directly. This design has advantages and disadvantages. In SQLite's target environments, the lack of a server is a major benefit, because no administrator is needed to start a server or repair one when it breaks. The main disadvantage is that features such as MVCC (multi-version concurrency control) are difficult to build without a server. It might be possible in theory, but the overhead would be too high. An audience member challenged this, saying they wanted to see how it could be done. The answer is that SQLite is a pure library linked directly into the client program, and it essentially translates SQL into disk accesses. The speaker plans to cover the details in a later talk.
Competing with fopen rather than server databases
SQLite is not trying to compete with PostgreSQL, Oracle, or MySQL. Its real competitor is fopen, the standard C function for opening files. Replacing fopen is the actual goal, so SQLite's mission is very different from that of the server databases. Five minutes remain, but the session is still open for questions, so the Q&A continues.
Bitmap indexes and consortium funding
One question asks what happens when more levels of optimization must be added, such as choosing between a complex index and bitmap indexes. SQLite's development is funded through the SQLite Consortium, a group of large companies that use SQLite in their products and depend on it for critical functions. Each member contributes a small amount of money every year to make sure the project continues. This model works well, and it currently supports three developers working on SQLite.
Serving big-iron users and small devices
Bloomberg recently joined the consortium. It had been using SQLite on large servers, which we call big iron. Those users want bitmap indexes, but phone and iPod makers do not, because bitmap indexes use more memory. Since the big-iron users help keep the project funded, bitmap indexes will be added for them. They will probably be a compile-time option, because bitmap indexes make the code larger and more complex. Phone and iPod developers can leave the option out to keep SQLite small and simple. Recently, phone makers have said they could accept a limit of 500 kilobytes instead of 250 kilobytes, since memory is getting cheaper. Whether they will keep bitmap indexes under that limit is still uncertain.
How bound values persist in the program
An audience member asked where variables are stored in the program's structure. In most database engines, a compiled program contains variables that are initialized when the program is built. In SQLite, these variables are always initialized to NULL. When a value is bound to a variable, the binding changes the program's initializer. For example, a variable x might be set to 1, 2, or 3, depending on the value bound to it. The binding persists across repeated runs of a prepared statement. It stays in effect until it is changed to something else. Several slides that would have explained this more clearly were cut from the talk.
Binding without regenerating bytecode
Binding a value does not require regenerating the bytecode. The bytecode is changed only slightly. Binding simply replaces a constant in the bytecode with the new value. No instructions need to be inserted or rewritten, so the change is small.
Closing the session
With no further questions, the session adjourns two minutes ahead of schedule.
Turn your watchlist into a reading routine
Bring your YouTube videos together, read summaries with key passages marked, and explore the full transcript. Save your own highlights with Pro.
Start with 5 free batteries. Each covers up to 30 minutes of a new summary.
New summaries depend on video availability and demand; processing may take time or require retry.