# Auto Insight AI (`eager_cornet/sql-explainer`) Actor

AutoInsight AI is your interactive AI-powered SQL tutor that helps you learn SQL the way professionals master it through guided practice, real examples, instant feedback, and visual execution results.

- **URL**: https://apify.com/eager\_cornet/sql-explainer.md
- **Developed by:** [vikash kumar](https://apify.com/eager_cornet) (community)
- **Categories:** AI, Developer tools, Other
- **Stats:** 3 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.01 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## 🧙‍♂️ SQL Explainer & Visualizer (AI Powered)

**Turn any SQL query (or English question) into a visual data story.**

[![Apify](https://img.shields.io/badge/Apify-Actor-green)](https://apify.com) [![Gemini](https://img.shields.io/badge/AI-Gemini%202.0-blue)](https://deepmind.google/technologies/gemini/)

This Actor is your **AI-powered SQL Professor and Analytics Assistant**. It doesn't just run queries; it understands them, explains them, fixes them, and visualizes the results—all automatically.

***

### 🚀 Key Features

#### 🧠 1. The "SQL Professor" Mode

Ask a conceptual question like *"What is a Window Function?"* or *"Explain LEFT JOIN"*.

- **Auto-Demo**: The Actor generates a valid SQL query to **demonstrate** the concept.
- **Deep Explanation**: Explains the concept, order of execution, and data flow.
- **Visual Proof**: Runs the query and shows you the result.

#### 🗣️ 2. Natural Language to SQL

Don't know SQL? Just ask in English.

- *"Show me the top 5 departments by average salary"*
- *"Calculate the 7-day moving average of sales"*
- The Actor converts it to optimized SQL automatically.

#### 🛠️ 3. Auto-Fix & Self-Healing

Made a typo? Forgot a `GROUP BY`?

- The Actor detects the error.
- **Gemini AI** analyzes the error message and **fixes the SQL** automatically.
- It retries execution without you lifting a finger.

#### 📊 4. Intelligent Visualization

No configuration needed.

- The AI analyzes your data and picks the **perfect chart** (Bar, Line, Pie, Scatter).
- Generates a beautiful, embeddable PNG chart.

#### 📑 5. Smart Insights Report

Get the "So What?" from your data.

- Generates a **professional one-paragraph report**.
- Highlights top performers, trends, and business implications.

#### 🧪 6. Zero-Config Execution

- **No Database Required**: The Actor generates realistic **dummy data** on the fly based on your query's schema.
- **In-Memory Engine**: Runs instantly using SQLite.

***

### 📖 How It Works

1. **Input**: You provide a SQL query OR a natural language question.
2. **Analysis**: Gemini AI analyzes the intent, structure, and logic.
3. **Data Gen**: We generate synthetic data matching your table names and columns.
4. **Execution**: The query runs against this data.
5. **Report**: We generate a **beautiful HTML Report** containing:
   - The Explanation
   - The Chart
   - The Insights
   - The Data Table

***

### 🎯 Use Cases

- **Education**: Learn SQL concepts by seeing them in action.
- **Debugging**: Paste a broken query and let the AI fix and explain it.
- **Quick Analytics**: Generate instant visualizations for presentations without setting up a database.
- **Hackathons**: Use it as a backend to power "Text-to-Insight" dashboards.

***

### 🔌 Input & Output

#### Input

- `sql`: (String) Your SQL query OR English question.
- `geminiApiKey`: (String, Optional) Your Google Gemini API Key.

#### Output

- **Analysis Report Tab**: A full HTML dashboard in the Apify UI.
- **Dataset**: JSON data with all raw results.
- **Key-Value Store**: `visualization.png` and `report.html`.

***

### 💎 Monetization

This Actor is available on the Apify Store with **Pay-Per-Event** pricing. You only pay when a successful analysis is generated.

***

*Built with ❤️ using Apify SDK, Python, and Google Gemini.*

# Actor input Schema

## `sql` (type: `string`):

The SQL query to analyze, or a natural language question to convert to SQL.

## `geminiApiKey` (type: `string`):

Optional: Provide a Google Gemini API Key for detailed AI explanations and smart visualization.

## Actor input object example

```json
{
  "sql": "SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY department"
}
```

# Actor output Schema

## `details` (type: `string`):

No description

## `visualization` (type: `string`):

No description

## `report` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "sql": "SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY department"
};

// Run the Actor and wait for it to finish
const run = await client.actor("eager_cornet/sql-explainer").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "sql": "SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY department" }

# Run the Actor and wait for it to finish
run = client.actor("eager_cornet/sql-explainer").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "sql": "SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY department"
}' |
apify call eager_cornet/sql-explainer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eager_cornet/sql-explainer"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/q0Ju6ldoOFysIrhfv/builds/QW6SsTsX8dfQxJFRf/openapi.json
