VillageSQL is a drop-in replacement for MySQL with extensions.
All examples in this guide work on VillageSQL. Install Now →
ai_prompt() adds one.
Standard Approach: Application-Layer Sentiment
The typical setup runs sentiment scoring outside MySQL — pulling rows to a Python script that calls a sentiment library or an AI API, then writing scores back. This works, but it splits your data pipeline: some logic lives in SQL, some in Python, and a bulk re-score requires running a script.With VillageSQL: Sentiment in SQL
Adding a numeric score
For trend analysis and averaging, ask for a 1–5 score instead of a label:Aspect-based sentiment
If you want sentiment broken down by topic — the product quality vs. shipping vs. customer service — ask for structured JSON output:Accuracy Notes
Fast, cheap models (Claude Haiku, GPT-4o mini) are reliable for straightforward positive/negative/neutral classification. Nuanced cases — sarcasm, mixed reviews, domain-specific language — benefit from a more capable model. If accuracy matters, validate a sample of model outputs against human labels before running a full backfill. For setup and provider options, see Connecting MySQL to AI APIs.Frequently Asked Questions
How is this different from text classification?
Sentiment analysis is a specific classification task focused on emotional tone. Classifying Text in MySQL with AI covers the general pattern; this guide shows sentiment-specific prompts and score-based output.Can I run sentiment analysis as rows are inserted?
Yes via trigger, but each INSERT will take 5–30 seconds while the API call runs. Better to run sentiment scoring in a scheduled batch job.What about non-English text?
Capable AI models handle many languages well. Specify the expected language in the prompt if accuracy degrades: “Rate the sentiment of this French review…”How do I handle NULL results?
ai_prompt() returns NULL on failure. Run the UPDATE batch loop until no NULL rows remain, with rate-limit-aware pacing in your application.
Troubleshooting
| Problem | Solution |
|---|---|
FUNCTION ai_prompt does not exist | Run INSTALL EXTENSION vsql_ai |
| Returns NULL | Check API key, max_execution_time, and model name |
| Score column fills with 0 instead of NULL | CAST('positive' AS SIGNED) returns 0 — model returned non-numeric text. Tighten prompt: “Reply with a single digit only, no other text.” |
| Inconsistent labels | Add “Reply with exactly one word” to prompt; normalize with post-UPDATE query |

