Quick revision
The short answer
An OR across two different columns stops the database from walking one index in created_at order, so it collects every matching ticket, sorts them all and keeps 50. We rewrite it as two branches, each reading the newest 50 tickets through an index on (assignee_id, created_at) or (reporter_id, created_at), combine them with UNION to drop tickets that match both, and sort the at most 100 rows that remain. The rewrite is longer and harder to maintain, so we keep it only when EXPLAIN ANALYZE shows that it pays.
What to remember
In this answer, we saw that an OR across assignee_id and reporter_id prevents reading one index in date order, so the database reads and sorts every matching ticket even with LIMIT 50. Splitting the query into two branches, each served by a composite index ending in created_at, combining them with UNION to remove duplicates, and sorting the small result reduces the work to about 100 rows. The cost is a longer, less obvious query and more indexes, so we keep it only when measurements on heavy users justify it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
An OR across two different columns stops the database from walking one index in created_at order, so it collects every matching ticket, sorts them all and keeps 50. We rewrite it as two branches, each reading the newest 50 tickets through an index on (assignee_id, created_at) or (reporter_id, created_at), combine them with UNION to drop tickets that match both, and sort the at most 100 rows that remain. The rewrite is longer and harder to maintain, so we keep it only when EXPLAIN ANALYZE shows that it pays.
Why this question is asked
Inbox-style screens, such as all tickets assigned to me or reported by me, newest first, are everywhere, and they are a classic place where a query is fast in development and slow once one user owns a few hundred thousand rows. Interviewers like this question because it combines index design, how the planner handles OR, and the honesty to measure before making SQL more complicated. In this answer, we will see why the original query struggles, rewrite it step by step, choose the indexes that make the rewrite work, and weigh what the rewrite costs.
1Why the OR Query Is Slow
An index on a column works like a sorted list of values with pointers to rows. A composite index on (assignee_id, created_at) is sorted first by assignee and then by date, so for assignee 7 it hands us that user's tickets already ordered by created_at. With ORDER BY created_at DESC LIMIT 50, the database could read the first 50 entries backwards and stop. That is the fast path we want.
The OR breaks it. The tickets we want live in two different places, one index sorted by assignee and another sorted by reporter, and no single index lists them in one created_at order. PostgreSQL's best option is usually a BitmapOr: it scans both indexes, builds a bitmap of matching row locations, reads every one of those rows, sorts them by date and keeps 50. MySQL can do something similar with an index_merge union. Both avoid a full table scan, but both must read and sort every matching ticket, and a heavy user can match 200,000 of them.
Notice the actual rows on the heap scan: 200,000 rows read to return 50. When the planner thinks the matches are a large share of the table, it may even choose a sequential scan instead. Either way, the LIMIT only helps after all the work is done.
2Rewriting It as Two Indexed Branches
The idea is to give each condition its own query, where each one can use the fast path, and merge the results. If the newest 50 overall exist, each of them must be among the newest 50 of its own branch, so asking each branch for 50 rows is enough.
6 messages in order. Play them, or step through them one at a time.
Each branch stops after 50 index entries, so the work no longer grows with the user's ticket count.
The parentheses matter: they apply ORDER BY and LIMIT to each branch, and the final ORDER BY and LIMIT apply to the combined result. The database reads at most 100 index entries and rows, removes duplicates and sorts 100 rows instead of 200,000. Notice too why we use UNION and not UNION ALL. A ticket that user 7 reported and was then assigned appears in both branches, and UNION removes such duplicates. UNION ALL would be cheaper but could show the same ticket twice. If we want UNION ALL's speed, the second branch can exclude the overlap with AND assignee_id IS DISTINCT FROM 7, which also handles tickets with no assignee correctly.
3Choosing the Indexes That Make It Work
The rewrite only helps if each branch can read its rows in date order, which needs composite indexes that start with the filtered column and continue with the sort column. Single-column indexes on assignee_id and reporter_id would find the rows but would still force a sort of all of them.
CREATE INDEX CONCURRENTLY builds the index without blocking writes, which matters on a large live table. Each new index also slows every insert and update a little and takes disk space, so if the old single-column indexes are now unused, we can drop them after checking pg_stat_user_indexes. In MySQL the same composite indexes work, and MySQL 8 accepts ORDER BY and LIMIT inside parenthesized UNION branches.
4Weighing the Trade-offs
The rewrite is not free. The query is longer, the intent is less obvious to the next reader, and ORMs make it awkward: plain JPQL in older versions has no UNION, although Hibernate 6 HQL supports set operations, and many teams fall back to a native query. There is also a subtle trap with UNION and SELECT *: duplicates are found by comparing whole rows, so a column type without an equality operator, such as json (but not jsonb), makes the query fail. Selecting ids in the UNION and joining back to tickets avoids that and keeps the deduplication cheap.
Pagination needs care as well. With OFFSET 1000, each branch would have to read 1,050 rows, so the cost comes back. Keyset pagination fits much better: each branch adds WHERE created_at < :lastSeen, and adding id as a tie-breaker in both the index and the ORDER BY keeps the order stable when two tickets share a timestamp.
Finally, the rule that matters most: measure. For a user with 300 tickets, the BitmapOr version may already take two milliseconds, and the rewrite gains nothing. We run EXPLAIN (ANALYZE, BUFFERS) on realistic heavy users before and after, and keep the rewrite only when the difference is real, writing the reason in a comment next to the query.
5Follow-up questions
Why not keep the OR and just add both composite indexes?
The planner may use the composite indexes inside the BitmapOr, but a bitmap scan loses index order, so it still has to fetch and sort every match. The order-preserving fast path only exists for one index at a time, which is why splitting the query into branches is what unlocks it.
Could the database do this rewrite for us?
Some planners transform OR into a union internally in limited cases, and planner improvements arrive in new versions, so check your version. We should not rely on it: if the plan shows a bitmap scan feeding a sort of many rows, the manual rewrite is the dependable fix.
How would you write this in Spring Data JPA?
The simplest route is a native query on the repository with the UNION text and a projection or entity result. With Hibernate 6, HQL also supports UNION, but limits inside each branch are easier to express in native SQL. Either way, a test should assert the result order and that a ticket matching both conditions appears once.
6Conclusion
In this answer, we saw that an OR across assignee_id and reporter_id prevents reading one index in date order, so the database reads and sorts every matching ticket even with LIMIT 50. Splitting the query into two branches, each served by a composite index ending in created_at, combining them with UNION to remove duplicates, and sorting the small result reduces the work to about 100 rows. The cost is a longer, less obvious query and more indexes, so we keep it only when measurements on heavy users justify it.
Open with
The problem is that the OR spans two columns, so no single index gives the rows in created_at order. PostgreSQL usually does a BitmapOr over the two indexes, which avoids a full scan but still fetches every matching ticket and sorts them before applying LIMIT 50; MySQL does a similar index_merge.
Then, if they want more
For a heavy user that is hundreds of thousands of rows for 50 results. I would rewrite it as two parenthesized branches, one WHERE assignee_id = 7 and one WHERE reporter_id = 7, each with ORDER BY created_at DESC LIMIT 50, combined with UNION, then ORDER BY created_at DESC LIMIT 50 on the outside.
With indexes on (assignee_id, created_at) and (reporter_id, created_at), each branch reads 50 entries backwards from its index and stops, so we sort at most 100 rows. I use UNION rather than UNION ALL because a ticket can match both conditions; if I want UNION ALL, the second branch excludes assignee 7.
The trade-offs are a longer query that ORMs handle poorly, two composite indexes that cost write time, and pagination that needs keyset cursors rather than OFFSET. So I would compare EXPLAIN ANALYZE before and after on a heavy user and keep the rewrite only if the gain is real.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6, MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Rewrite this for a large table so it can use indexes on both columns:": https://scrivio-interview-library.netlify.app/databases/query-optimization/5c61d51af3/