database-query-subagent

database-query-subagent is a skill for Claude Code, Codex from khalilbenaz/claude-skills-collection. It costs 87 tokens per session (2,876 once invoked), scanned A, original, MIT.

A read-only AI helper that turns plain-language questions into database queries and explains the results. NL2SQL means converting natural-language questions into SQL, the language used to query many databases.

In plain words
What is it for?
Building conversational database search, assisted business reporting, complex data analysis, and follow-up questions about query results.
Why use it?
It reduces the need to write SQL manually while checking the database connection, discovering the schema, and limiting queries to reading data.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one. Also seen: mentions subagents.

Good fit Building conversational database search, assisted business reporting, complex data analysis, and follow-up questions about query results.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/khalilbenaz/claude-skills-collection/database-query-subagent
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add khalilbenaz/claude-skills-collection --skill database-query-subagent
Clone the repo
git clone --depth 1 https://github.com/khalilbenaz/claude-skills-collection

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for database-query-subagent

README.md
[![agentmods](https://agentmods.dev/badge/skills/khalilbenaz/claude-skills-collection/database-query-subagent/github.svg)](https://agentmods.dev/skills/khalilbenaz/claude-skills-collection/database-query-subagent)
Your own site
<a href="https://agentmods.dev/skills/khalilbenaz/claude-skills-collection/database-query-subagent"><img src="https://agentmods.dev/badge/skills/khalilbenaz/claude-skills-collection/database-query-subagent/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for database-query-subagent

Your own site · 80×15
<a href="https://agentmods.dev/skills/khalilbenaz/claude-skills-collection/database-query-subagent"><img src="https://agentmods.dev/badge/skills/khalilbenaz/claude-skills-collection/database-query-subagent.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 87 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,876 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. Third-party audits
  • NVIDIA SkillSpector pass 7 Sept 2026
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00087 $0.02876
Opus 5 $0.00044 $0.01438
Sonnet 5 $0.00017 $0.00575
Haiku 4.5 $0.00009 $0.00288

Measured 10d ago against content hash 7a5e8ad2ffae, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-10, from the pricing page.

Security

Grade A, and why

database-query-subagent scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 10d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

agent-skills/database-query-subagent/SKILL.md · 315 lines

How it starts

The opening of the file, as written. The whole thing — 315 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Database Query Sub-Agent

Cas d'usage

Déléguer à ce sous-agent toute interrogation DB depuis un agent parent : NL2SQL (question → SQL), analyse de données complexes, BI assistée par IA, drill-down conversationnel multi-tour. Ne pas utiliser pour des mutations — ce sous-agent est en lecture seule par défaut.


Workflow (10 étapes)

1. Validation des inputs

Recevoir et valider avant toute génération de SQL :

required = ["question", "connection.db_type", "connection.host", "connection.database"]
# Tester la connexion : ping + SELECT 1
# Si échec → retourner immédiatement errors=[{"type": "connection_error", ...}]

Defaults : read_only=True, max_rows=1000, timeout_s=30.


2. Découverte du schéma

Si schema non fourni, l'inférer automatiquement :

-- PostgreSQL / MySQL
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, ordinal_position;

-- SQLite
SELECT name, sql FROM sqlite_master WHERE type='table';

-- SQL Server
SELECT t.name, c.name, tp.name, c.is_nullable
FROM sys.tables t
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types tp ON c.user_type_id = tp.user_type_id;

Construire un DDL simplifié (max ~2 000 tokens) à injecter dans le prompt de génération.


3. NL → SQL (génération)

Prompt structuré :

Schéma DDL :
<DDL des tables pertinentes uniquement>

Question : <question utilisateur>
Dialecte : <db_type>
Contraintes : lecture seule, LIMIT max_rows

Règles :
- Préférer les CTEs aux sous-requêtes imbriquées
- Alias explicites sur toutes les colonnes ambiguës
- Pas de SELECT * sur tables volumineuses
- Exemples few-shot si disponibles en session_context

Critères de sélection des tables pertinentes : similarité sémantique entre la question et les noms de tables/colonnes (embedding cosine > 0.7, ou matching de mots-clés en fallback).


4. Validation avant exécution

import sqlglot

def validate_query(sql: str, db_type: str, schema: dict, read_only: bool) -> list[str]:
    errors = []
    # 1. Parse syntaxique
    try:
        parsed = sqlglot.parse_one(sql, dialect=db_type)
    except sqlglot.errors.ParseError as e:
        errors.append(f"syntax_error: {e}")
        return errors

    # 2. Vérifier colonnes et tables vs schéma
    for table in parsed.find_all(sqlglot.exp.Table):
        if table.name not in schema["tables"]:
            errors.append(f"unknown_table: {table.name}")

    # 3. Bloquer mutations si read_only
    if read_only:
        forbidden = (sqlglot.exp.Drop, sqlglot.exp.Delete,
                     sqlglot.exp.Update, sqlglot.exp.Insert,
                     sqlglot.exp.Create, sqlglot.exp.AlterTable)
        for node in parsed.walk():
            if isinstance(node, forbidden):
                errors.append(f"mutation_blocked: {type(node).__name__}")
    return errors

Read the full file on GitHub · 315 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 10d ago First seen · 315 lines · 87 tokens per session scan A 7a5e8ad2ffae

Subscribe to this mod's changes

database-query-subagent is a skill published in the GitHub repository khalilbenaz/claude-skills-collection (22 stars, last pushed 16d ago), licensed MIT. It adds 87 tokens to every session and 2,876 once invoked, about $0.0004 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.