Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples in this guide work on VillageSQL. Install Now →
Sentiment analysis tells you whether text expresses positive, negative, or neutral feeling. The most common use case is product reviews and support tickets — knowing at a glance whether a customer is happy or frustrated without reading every row. MySQL has no built-in sentiment function. VillageSQL’s 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

Sentiment analysis is a classification task. The prompt specifies the scale and asks for a single-word result:
Once labeled, query sentiment like any other column:

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

See also