How do I assign a row number within each category?
Quick answer
Use ROW_NUMBER() OVER (PARTITION BY category ORDER BY price, product_id). PARTITION BY category restarts the count at 1 for each category; ordering by price puts lower prices first, and product_id breaks price ties consistently. Add an outer ORDER BY if you also want to control how the completed results are displayed.
The question, the details, the next step.
A practical checklist
Use
PARTITION BY categoryto restart numbering within each category.Choose
ORDER BY priceorORDER BY price DESCfor the price direction you want.Add a unique tie-breaker if tied prices need a predictable order.
Use an outer
ORDER BYto control the displayed result order.
A few more useful answers
Do equal prices get the same row number?
No. ROW_NUMBER() gives each row its own consecutive number. Add a tie-breaker to determine the order of rows with equal prices. [S1]
Does the window’s `ORDER BY` sort the final results?
Not by itself. It determines the numbering order; use an outer ORDER BY when you want a particular display order. [S1]
Can I number the most expensive product first?
Yes. Use ORDER BY price DESC in the window definition. Include a tie-breaker if you need a predictable order for equal prices.
Sources
References used for this guide.
- [S1] SQLite Window Functions: partitions and row_number() sqlite.org · Checked
