Indexes, Error Handling, and In-Memory Tables
Now that you know the basics, it’s time to cover the features needed to create robust applications using SQLite. Features such as creating primary and other keys, using in-memory tables, and error handling are all necessary to keep your site up and running in a responsive manner.
Indexes
Adding an index, also called a key, is the easiest way to improve application performance. When SQLite searches a database without keys, it needs to look at every single row in the table to check for matches. However, after you apply an index to the search fields, SQLite can often avoid this time-consuming process. Instead, it consults a specially constructed record that allows SQLite to quickly look up a field’s location within the table.
If you know ahead of time that the data in a particular field in your
database is going to be unique (i.e., each value will appear in only
one record for that field), then you should declare the field
UNIQUE in your CREATE TABLE SQL
statement. SQLite automatically indexes UNIQUE
fields.
CREATE TABLE users (username TEXT UNIQUE, password TEXT);
In a web application, a username field is often
unique, whereas a password field is not. When
username is UNIQUE, SQLite
creates a key, since SQLite needs to scan the column to protect
against duplicate entries every time you insert a record. This
prevents the database from having two users named
rasmus. Also, you often query against fields that
are important enough to be UNIQUE ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access