The Day SQLite Told Me: "Too Many Terms in Compound SELECT"

A few days ago, I was running a database migration in an Android app. Nothing fancy—just creating the PAGES table with all 604 rows of data in a single INSERT statement:

INSERT INTO PAGES (page, startSurah, startAyah, endSurah, endAyah) VALUES
  (1, 1, 1, 1, 7),
  (2, 1, 8, 1, 16),
  ...
  (604, 114, 1, 114, 6);

Everything worked perfectly until we get an exception below from our Android 5 device users.

android.database.sqlite.SQLiteException: too many terms in compound SELECT (code 1)

Wait. What? I wasn’t even running a SELECT query!

---

Digging Deeper

After some investigation, I found out something interesting:

When you do a multi-row INSERT ... VALUES (...), SQLite doesn’t keep it as-is. Instead, it rewrites it internally into something like this:

INSERT INTO PAGES (page, startSurah, startAyah, endSurah, endAyah)
SELECT 1, 1, 1, 1, 7
UNION ALL SELECT 2, 1, 8, 1, 16
...
UNION ALL SELECT 604, 114, 1, 114, 6;

So in reality, I was running a big compound SELECT.

---

The Hidden Limit on Android 5

SQLite has a compile-time limit called SQLITE_LIMIT_COMPOUND_SELECT.

  • On Android 5 (SQLite 3.8.x), the limit is 500 terms.
  • Each row in my INSERT turns into one term of that compound SELECT.
  • 604 rows = 604 terms → boom, limit exceeded.

That’s why the error popped up at 604 but would’ve worked if I had stopped at 500.

---

How I Fixed It

The solution turned out to be simple: split the insert into smaller chunks.

// First batch (300 rows max)
INSERT INTO PAGES (...) VALUES (...), (...), ...;

// Second batch (remaining 304 rows)
INSERT INTO PAGES (...) VALUES (...), (...), ...;

---

Lessons Learned

That day I learned two important things about SQLite on Android 5:

  1. Multi-row INSERTs get rewritten into SELECT ... UNION ALL.
  2. There’s a hard 500-row limit on those compound selects in SQLite 3.8.x (the version shipped with Android 5).

So if you’re writing migrations or seeding data for older Android versions, always keep this in mind. Anything above 500 rows in a single insert will fail with:

SQLiteException: too many terms in compound SELECT