How can I use CASE to label values in a SELECT result?
Quick answer
Put a CASE expression in your SELECT list, with a WHEN condition and THEN label for each category. SQLite checks searched CASE conditions from left to right and returns the result for the first true condition, so put narrower or more specific ranges before broader ones. Add ELSE for a fallback label. This changes the query result, not the stored stock values. [S1]
The question, the details, the next step.
A practical checklist
Replace
inventory,item_name, andstock_countwith your actual table and column names.Write down what each label means and choose the cutoff values for your use.
Put exact or narrower conditions before broader conditions that could also match.
Choose an ELSE label, or deliberately account for the NULL result if no condition matches.
Check example boundary counts, including zero, the cutoff, and a value just above it.
A few more useful answers
Does CASE update the stock count in the table?
No. In this SELECT example, CASE supplies a value in the query result; it does not update stored data. [S1]
What happens if no WHEN condition matches and I omit ELSE?
SQLite returns NULL for that CASE result when there is no matching WHEN and no ELSE. [S1]
Can I change the label thresholds?
Yes. Replace the example conditions with your chosen rules, and keep potentially overlapping conditions in the order you want them considered.
Sources
References used for this guide.
- [S1] SQLite SQL Language Expressions: CASE expression sqlite.org · Checked
