惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
C
Cisco Blogs
The Hacker News
The Hacker News
T
Threatpost
S
Schneier on Security
K
Kaspersky official blog
Spread Privacy
Spread Privacy
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
NISL@THU
NISL@THU
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
Security Latest
Security Latest
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News and Events Feed by Topic
爱范儿
爱范儿
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cisco Talos Blog
Cisco Talos Blog
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
Forbes - Security
Forbes - Security
博客园 - 三生石上(FineUI控件)
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic
V
V2EX
Webroot Blog
Webroot Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
L
LangChain Blog
W
WeLiveSecurity
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Natural Language Query Interface for Your Database: A Developer's Blueprint
Vivek Kumar · 2026-06-16 · via DEV Community

Every product team eventually hits the same wall. Marketing wants to know which signups came from last week's campaign. Support wants a list of customers on the Pro plan who opened a ticket in the last 48 hours. The founder wants MRR by cohort, broken down by acquisition channel, by yesterday at 9am.

And every time, someone pings the nearest engineer to write yet another one-off SQL query.

The dream is obvious: let people ask questions in plain English and get answers from the database. For years, that dream lived in expensive enterprise BI tools. In 2026, with capable LLMs available behind an API call, you can build a credible natural language query interface yourself — or use something like Draxlr that ships with AI-powered SQL generation already built in. If you want to understand how it works under the hood, or roll your own, this post walks through what such a system actually looks like: the architecture, the SQL plumbing, the prompt design, and the production failure modes you'll want to plan for before your first user types a question.

What "Natural Language to SQL" actually means

At its simplest, a text-to-SQL system is a function:

question (string) -> SQL query (string) -> result (rows)

The naive implementation is one prompt to GPT-style model: "Here's my schema, here's the question, write a SQL query." That works for toy demos and falls apart the moment you point it at a real database with 80 tables, 14 of which are named some variation of users.

A production-grade interface looks more like this:

question
   |
   v
[ schema retrieval ]  <-- pull only relevant tables
   |
   v
[ prompt assembly ]   <-- schema + examples + guardrails
   |
   v
[ SQL generation ]    <-- LLM call
   |
   v
[ validation ]        <-- parse, lint, dry-run
   |
   v
[ safe execution ]    <-- read-only role, row limits, timeouts
   |
   v
result + the SQL it ran (always show this)

Each of those stages is a thing you build. Let's walk through them.

Step 1: Schema retrieval (don't dump everything)

The single biggest accuracy lever is the schema context you feed the model. Dumping your entire schema into the prompt sounds tempting and is almost always wrong: it blows your context window, costs more, and — counterintuitively — makes the model less accurate because it has to pick the right tables out of a haystack.

The fix is retrieval. Treat your schema like a knowledge base, embed it, and pull only what's relevant to the question.

Start by capturing a clean description of every table:

SELECT
  c.table_name,
  c.column_name,
  c.data_type,
  pgd.description AS column_comment
FROM information_schema.columns c
LEFT JOIN pg_catalog.pg_statio_all_tables st
  ON st.schemaname = c.table_schema AND st.relname = c.table_name
LEFT JOIN pg_catalog.pg_description pgd
  ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position
WHERE c.table_schema = 'public'
ORDER BY c.table_name, c.ordinal_position;

For each table, build a small text document that the LLM can actually read:

Table: subscriptions
Description: One row per customer subscription. A user can have at most one
active subscription at a time. `status` is one of active, paused, cancelled.
Columns:
  - id              (uuid, PK)
  - user_id         (uuid, FK -> users.id)
  - plan_id         (uuid, FK -> plans.id)
  - status          (text)
  - mrr_cents       (integer) -- monthly recurring revenue in cents
  - started_at      (timestamptz)
  - cancelled_at    (timestamptz, nullable)
Sample rows:
  id=a1.., user_id=u3.., plan_id=p_pro, status=active, mrr_cents=4900

Embed each of those documents with any embedding model, store the vectors, and at query time embed the user's question and pull the top 5–10 most similar tables. This is plain RAG, applied to schema instead of documents.

The payoff is dramatic. A question like "how many users upgraded to Pro last month?" will retrieve users, subscriptions, and plans — and leave the 70 other tables out of the prompt entirely.

Step 2: Prompt assembly

Once you have the relevant tables, the prompt itself follows a predictable shape:

  1. A system message defining the role and the dialect.
  2. The retrieved schema documents.
  3. A few worked examples (few-shot).
  4. Hard rules ("read-only", "always LIMIT 1000", "use ISO dates").
  5. The user's question.

Here's a stripped-down version in pseudocode:

def build_prompt(question, tables, examples):
    return f"""You are a PostgreSQL expert. Generate a single SELECT query
to answer the user's question. Rules:
- Use only the tables and columns shown below.
- Always include LIMIT 1000.
- Use ISO date literals (e.g. '2026-05-01').
- Never write INSERT, UPDATE, DELETE, DROP, or DDL.
- If the question is ambiguous, return a JSON object
  {{"clarify": "..."}} instead of SQL.

## Schema
{format_tables(tables)}

## Examples
{format_examples(examples)}

## Question
{question}

Return only the SQL, no explanation."""

The two underrated pieces here are the examples and the clarification escape hatch.

A handful of question/SQL pairs from your domain teaches the model your conventions — that mrr_cents is in cents, that "active users" means status = 'active' AND last_seen_at > now() - interval '30 days', that you always join on tenant_id. Three good examples often beat a thousand words of instruction.

The clarification hatch is the difference between a tool that hallucinates confidently and one that admits when a question is too vague. Ambiguous natural language is the #1 source of bad SQL, and giving the model a way to ask back is far better than letting it guess.

Step 3: Validation before execution

Never run an LLM-generated query straight against your database. There are three layers worth wiring up.

Parse it. Run the SQL through a parser like sqlglot or pgsql-parser. If it doesn't parse, you have a clean signal to either retry or report the error — no need to wait for the database to reject it.

Lint it. Walk the parsed AST and reject anything that isn't a SELECT. Reject queries that reference tables outside your allowed list. Reject queries without a LIMIT. This is your defence against a creative model that decides DELETE FROM users is a reasonable answer.

from sqlglot import parse_one, exp

def is_safe(sql, allowed_tables):
    tree = parse_one(sql, read="postgres")
    if not isinstance(tree, exp.Select):
        return False, "only SELECT allowed"
    for t in tree.find_all(exp.Table):
        if t.name not in allowed_tables:
            return False, f"table {t.name} not allowed"
    if not tree.args.get("limit"):
        return False, "missing LIMIT clause"
    return True, None

Dry-run it. PostgreSQL has EXPLAIN. Run the query under EXPLAIN (not EXPLAIN ANALYZE — that executes it) to confirm the planner accepts it. If EXPLAIN returns an estimated cost above some threshold, refuse to run it or warn the user.

Step 4: Safe execution

The query has parsed, linted, and been planned. Now run it — but not as your application's regular DB user.

Create a dedicated read-only role with the minimum privileges needed:

CREATE ROLE nl_query_runner LOGIN PASSWORD '...';

REVOKE ALL ON ALL TABLES IN SCHEMA public FROM nl_query_runner;
GRANT SELECT ON users, subscriptions, plans, events TO nl_query_runner;

ALTER ROLE nl_query_runner SET statement_timeout = '10s';
ALTER ROLE nl_query_runner SET default_transaction_read_only = on;

Statement timeouts catch runaway queries. default_transaction_read_only is belt-and-braces protection in case your lint layer ever has a bug. Granting SELECT only on the specific tables you've exposed means even a perfectly-crafted injection can't touch your secrets table.

For multi-tenant apps, layer Postgres row-level security on top, so even a query like SELECT * FROM subscriptions only sees the calling tenant's rows. (I wrote about this in a previous post on row-level security for embedded dashboards.)

A realistic end-to-end example

Imagine a SaaS analytics app where a user types:

"What was our MRR from Pro customers in April?"

Here's what happens:

  1. Retrieval pulls subscriptions, plans, and users.
  2. Prompt assembles those tables plus three example queries.
  3. Generation produces:
   SELECT SUM(s.mrr_cents) / 100.0 AS mrr_dollars
   FROM subscriptions s
   JOIN plans p ON p.id = s.plan_id
   WHERE p.name = 'Pro'
     AND s.status = 'active'
     AND s.started_at <= '2026-04-30'
     AND (s.cancelled_at IS NULL OR s.cancelled_at > '2026-04-30')
   LIMIT 1000;

  1. Validation parses cleanly, only references allowed tables, has a LIMIT.
  2. Execution runs under the read-only role and returns:

The UI shows the answer and the SQL that produced it. Always show the SQL. Users learn to trust the system faster when they can see its work, and your power users will start tweaking the SQL directly.

Common mistakes and gotchas

A few traps you'll hit if you don't plan for them:

Trusting the model on dates. LLMs are weirdly bad at "last week" vs. "the last 7 days" vs. "the previous calendar week". Resolve relative time expressions in your code before generating SQL, and inject explicit dates into the prompt.

Ambiguous column names. If you have users.created_at and subscriptions.created_at, a question like "how many created this month?" is genuinely ambiguous. Detect this and fall back to the clarification hatch instead of guessing.

Pre-aggregated columns. If you have a daily_metrics rollup table, the model may not know whether to query it or recompute from raw events. Document this explicitly in the table description: "Prefer this table for date-based aggregations; events table only for event-level analysis."

Joins that explode. A model can produce a cartesian join with a missing condition and pull back a billion rows. The EXPLAIN cost check and the statement_timeout are your safety net.

Currency, units, and time zones. mrr_cents is not mrr_dollars. started_at might be UTC; the user's "April" might mean Pacific Time. Encode these in your schema documentation and your few-shot examples, or expect surprising answers.

Showing only the answer, not the SQL. This destroys trust. The first time a user gets a number that looks off and has no way to inspect it, they'll stop using your tool. Always show the query.

Key takeaways

A practical natural-language-to-SQL interface is not a single LLM call. It's a small pipeline: retrieve the relevant schema, assemble a tight prompt with examples and rules, generate the SQL, validate it before it ever touches the database, and run it under a tightly-scoped role. The LLM is the interesting part, but the boring infrastructure around it — schema retrieval, parsing, linting, read-only roles, timeouts — is what separates a demo from a product.

Build for the failure cases from day one. Add a clarification path for ambiguous questions. Always show the generated SQL. Log every question and query so you can mine them for new few-shot examples. The systems that work in production are the ones that treat the LLM as a junior analyst whose output always gets reviewed, not as an oracle.

Over to you

Have you built a natural language interface for your own database, or are you using one in a product? What broke first when real users started typing into it? Drop your war stories — and the tools you reached for — in the comments. I'm especially curious which retrieval strategies have worked for people with very large or very messy schemas.