How do I select the top three items within each category?
Quick answer
In SQLite, calculate row_number() for each category, ordering by sales from highest to lowest, then filter to positions 1 through 3 in an outer query. Add a unique item ID as a tie-breaker for a consistent three-item cutoff. If you want to include every item tied at third place, use rank() instead; that can return more than three items in a category. [S1]
The question, the details, the next step.
A practical checklist
Confirm the table name and the category, item ID, item name, and sales columns.
Decide whether the cutoff means exactly three positions or all items tied at third place.
For a three-position cutoff, use
row_number()withORDER BY sales DESCand a suitable tie-breaker.For a tie-inclusive cutoff, use
rank()ordered by sales and filter withsales_rank <= 3.Add an outer
ORDER BYif the displayed row order matters.
A few more useful answers
Why include `item_id` in the `row_number()` ordering?
It provides a tie-breaker when sales values match, so tied items receive distinct positions in a consistent order. Choose a column that makes sense for your data; the example assumes item_id is suitable. [S1]
Can the query return fewer than three items for a category?
Yes. If a category has fewer than three rows, the filter returns the rows available. The cutoff selects existing rows; it does not create additional ones.
Does ordering inside the window sort the final results?
No. Window ordering determines ranking, while the outer query’s ORDER BY controls display order. Add an outer ordering clause if you want results grouped and ranked visibly. [S1]
Sources
References used for this guide.
- [S1] SQLite window functions: partitioned row numbering and ranking sqlite.org · Checked
