Skip to main content

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

All examples in this guide work on VillageSQL. Install Now →
Text classification — assigning rows to categories based on content — usually means exporting data to a Python script, calling an AI model, and importing results back. VillageSQL’s ai_prompt() lets you do the classification directly in SQL, keeping the logic close to the data and eliminating the export/import cycle.

The Problem: Classification Outside SQL

The typical workflow without VillageSQL:
This works, but the classification logic lives in application code. Migrations, backfills, and one-off relabels all require running a script rather than a SQL query.

With VillageSQL: ai_prompt() as a Classifier

The key to reliable classification is a tight prompt: enumerate the exact categories, tell the model to return only one of them, and optionally give an example.

Validating classification output

Models occasionally return unexpected output. Store results as-is and validate separately:

Multi-label classification

When a row can belong to more than one category, ask for a JSON array and store it in a JSON column:

Building a confidence score

Ask the model to return structured JSON with both a label and a confidence level:

Prompt Patterns That Work

Give the model fewer categories to choose from for better accuracy. More than 5–6 options degrades reliability for fast/cheap models. For setup and provider options, see Connecting MySQL to AI APIs. For broader ai_prompt() usage patterns, see Running AI Models from MySQL Queries.

Frequently Asked Questions

How accurate is AI classification compared to a trained model?

A capable model like Claude Haiku achieves high accuracy on straightforward classification tasks without any training data. For domain-specific categories with subtle distinctions, you may need to provide examples in the prompt or use a larger model.

Can I classify rows as they’re inserted using a trigger?

Yes, but use caution — a trigger that calls ai_prompt() on every INSERT makes every write take 5–30 seconds. Better to classify in a periodic batch job and accept a short delay before labels are available.

How do I handle rows where the model returns NULL?

ai_prompt() returns NULL when the API call fails. In your batch loop, keep running UPDATE until no NULLs remain, with retry logic for transient failures.

What model should I use for classification?

Start with claude-haiku-4-5-20251001 or gpt-4o-mini — both are fast and cheap. Step up to a more capable model only if accuracy is unacceptable.

Troubleshooting

See also