When building a user table for an asset management system, I wanted to identify users by numeric ID and let each person log in with their own username. As I remember it, my question was this: if SQLite can guarantee a username is unique, does it still have to read from the first row to the last to find that user?
In an ordinary SQLite table, looking up an ID declared INTEGER PRIMARY KEY can go directly to that row. Declaring the username UNIQUE generally makes SQLite create a unique index, which WHERE user_name = ? can use during login. Both declarations give the database a way to locate data quickly. To see the path a particular query actually takes, look at the query plan.12
How does SQLite look someone up by ID, username, or nickname?
Create a simplified user table in an empty database. Login names must be unique, but nicknames can repeat. Two of the following three people go by “小林”.
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
user_name TEXT NOT NULL UNIQUE,
user_nickname TEXT NOT NULL
);
INSERT INTO users VALUES
(1, 'lin', '小林'),
(2, 'chen', '小陈'),
(3, 'lan', '小林');
Put EXPLAIN QUERY PLAN before a SELECT and SQLite explains how it plans to find matching rows. Below are three equality queries on the same table and their plans in SQLite 3.45.1.3
EXPLAIN QUERY PLAN SELECT * FROM users WHERE user_id = 1;
EXPLAIN QUERY PLAN SELECT * FROM users WHERE user_name = 'lin';
EXPLAIN QUERY PLAN SELECT * FROM users WHERE user_nickname = '小林';
| Condition | Detail from the query plan | How records are found |
|---|---|---|
| ID equals 1 | SEARCH users USING INTEGER PRIMARY KEY (rowid=?) | Each row of an ordinary table has an integer rowid. Here user_id is that number, so SQLite can look up the row directly. |
| Login name equals lin | SEARCH users USING INDEX sqlite_autoindex_users_1 (user_name=?) | SQLite finds the row number for the login name in the unique index, then uses the row number to retrieve the whole row. |
| Nickname equals 小林 | SCAN users | The nickname column has no index yet. SQLite checks each row to find both people called “小林”. |
The documentation includes an easily overlooked qualifier: “In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database.”1 The first row above is an exception. The integer primary key uses the table’s rowid directly, so there is no separate ID index to maintain. In the second row, sqlite_autoindex_users_1 was created with the UNIQUE constraint when the table was defined. There is no need to add an identical index for login names.
Can a query use an index when nicknames repeat?
Keep both entries for “小林”, add an ordinary index on the nickname, and run the earlier query again.
CREATE INDEX users_nickname_idx ON users(user_nickname);
EXPLAIN QUERY PLAN SELECT * FROM users WHERE user_nickname = '小林';
The result is now SEARCH users USING INDEX users_nickname_idx (user_nickname=?). The index places entries with the same nickname together, so the database can locate both rows for “小林”. The username index conveys one extra fact: an equality lookup on a given non-null login name can match at most one row. That answers my original schema question. For nickname lookups, an ordinary index works. Declare the column UNIQUE only if the application really forbids duplicate names. This three-row example helps read the plan. Actual execution time also depends on table size and how many rows match.2
Can a table have two primary keys?
SQLite allows at most one primary key per table, but that key can consist of multiple columns. The declaration depends on which values must be unique together. The SQLite Tutorial contacts example illustrates this: the contact ID is the primary key and the email is separately NOT NULL UNIQUE. Changing the ID does not permit an existing email address to be reused.45
I encountered two cases in the asset management system.6
- The
userstable usesuser_idas its integer primary key and separately declaresuser_nameasNOT NULL UNIQUE. Two records with different IDs still conflict if their login names match. A composite key on(user_id, user_name)alone would allow two different IDs to share a login name. - The
asset_actionsaction parameters table usesPRIMARY KEY (action_name, asset_type, parameter_name). One action can have multiple parameters, and a parameter name can recur in another action. My/pk-error-testinserted the same three non-null values repeatedly to test how the backend handled a duplicate combination. The original table allowedNULLinparameter_name. In this kind of ordinary SQLite table, a combination containingNULLcan repeat. If every parameter must have a name, the column also needsNOT NULL.4
Another field on the users table deserves its own discussion. The caller supplies the login name, but SQLite can fill in the creation time when the row is inserted. See How can SQLite fill in the creation time automatically when inserting a row?.
Footnotes
-
SQLite. (n.d.). CREATE TABLE, §3.6 “UNIQUE constraints”, para. 3. SQLite Documentation. Unique indexes and exceptions ↩ ↩2
-
SQLite. (n.d.). Query planning, §§1.2–1.5. SQLite Documentation. Looking up data by rowid and by index ↩ ↩2
-
SQLite. (n.d.). EXPLAIN QUERY PLAN, §1.1 “Table and Index Scans”. SQLite Documentation. Reading SCAN and SEARCH ↩
-
SQLite. (n.d.). CREATE TABLE, §3.5 “The PRIMARY KEY”. SQLite Documentation. Composite primary keys and NULL ↩ ↩2
-
SQLite Tutorial. (n.d.). SQLite UNIQUE constraint, “Defining a UNIQUE constraint for one column example”. Contacts table definition ↩
-
borui. (2025, April 22). Fix actions endpoint error handling; add user table creation [Commit dfc8bd4]. GitHub. Definitions of both tables · Test route for primary key conflicts ↩