{"slug": "how-to-use-ai-to-write-sql-queries-from-plain-english", "title": "How to Use AI to Write SQL Queries from Plain English", "summary": "A developer outlines a structured method for using AI assistants to generate accurate SQL queries from plain English descriptions. The approach involves providing table definitions, using a specific prompt template, and iteratively verifying results through explanation and edge-case testing. The workflow aims to produce production-ready queries in three to four messages.", "body_md": "If you've ever stared at a complex schema and spent 20 minutes writing a query you could describe in one sentence, this walkthrough is for you. I'll show you exactly how to prompt an AI assistant to generate accurate, production-ready SQL from plain English — including the context you need to provide, the prompts that work, and how to verify what comes back.\n\nThe usual failure mode: you paste a vague question into ChatGPT or Claude, get back a query that looks plausible, run it, and get wrong results or an error. The fix isn't a better AI — it's a better prompt. AI models write SQL accurately when you give them the same context a senior teammate would need.\n\nNever ask for a query without first providing your table definitions. Copy the `CREATE TABLE`\n\nstatements directly from your database.\n\n```\n-- Paste this into your prompt first\nCREATE TABLE orders (\n  id SERIAL PRIMARY KEY,\n  customer_id INT NOT NULL,\n  status VARCHAR(20) NOT NULL,  -- 'pending', 'shipped', 'cancelled'\n  total_amount NUMERIC(10, 2),\n  created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\nCREATE TABLE customers (\n  id SERIAL PRIMARY KEY,\n  email VARCHAR(255) UNIQUE NOT NULL,\n  signup_date DATE NOT NULL,\n  plan VARCHAR(20) DEFAULT 'free'  -- 'free', 'pro', 'enterprise'\n);\n```\n\nIf your schema is large, include only the tables relevant to your question.\n\nUse this template every time:\n\n```\nYou are a SQL expert working with PostgreSQL.\n\nHere are my table definitions:\n[PASTE SCHEMA HERE]\n\nWrite a query that: [PLAIN ENGLISH DESCRIPTION]\n\nRequirements:\n- Use CTEs if the logic has more than one step\n- Add a comment explaining any non-obvious join condition\n- Do not use SELECT * — name every column\n```\n\n**Example request:**\n\n```\nWrite a query that returns, for each pro or enterprise customer who signed up\nin the last 90 days, their email, total number of orders, and total spend —\nbut only where total spend exceeds $500. Sort by total spend descending.\n```\n\n**What the AI returns:**\n\n```\n-- Customers on paid plans, signed up in the last 90 days\nWITH recent_paid_customers AS (\n  SELECT id, email\n  FROM customers\n  WHERE plan IN ('pro', 'enterprise')\n    AND signup_date >= CURRENT_DATE - INTERVAL '90 days'\n),\ncustomer_order_totals AS (\n  SELECT\n    c.email,\n    COUNT(o.id)          AS order_count,\n    SUM(o.total_amount)  AS total_spend\n  FROM recent_paid_customers c\n  -- Left join so customers with zero orders still appear; filter below\n  JOIN orders o ON o.customer_id = c.id\n  WHERE o.status != 'cancelled'\n  GROUP BY c.email\n)\nSELECT\n  email,\n  order_count,\n  total_spend\nFROM customer_order_totals\nWHERE total_spend > 500\nORDER BY total_spend DESC;\n```\n\nClean, readable, and correct on the first try — because the prompt had enough context.\n\nAsk the AI to explain the query back to you in plain English:\n\n```\nExplain this query step by step. Call out any assumptions you made\nabout the data or business logic.\n```\n\nThis surfaces hidden assumptions fast. If the explanation doesn't match your intent, correct it in the next message — the model retains the schema context in the same conversation.\n\nFollow up with edge-case questions in the same thread:\n\n```\nWhat happens if a customer has no orders at all? Will they appear in results?\nRewrite using a LEFT JOIN if needed so they show up with zero values.\n```\n\nThe model will revise the query and explain the change. This loop — generate, explain, stress-test, revise — usually gets you to a production-safe query in three to four messages.\n\n`CREATE TABLE`\n\nstatements`EXPLAIN ANALYZE`\n\non the result for any query touching large tablesThat's the full loop. No magic — just structured context.\n\nI break down one workflow like this every week in The AI Leverage Weekly — practical, no fluff, free. Subscribe: [https://theaileverageweekly.beehiiv.com/subscribe?utm_source=devto&utm_medium=article&utm_campaign=medium_w9](https://theaileverageweekly.beehiiv.com/subscribe?utm_source=devto&utm_medium=article&utm_campaign=medium_w9)", "url": "https://wpnews.pro/news/how-to-use-ai-to-write-sql-queries-from-plain-english", "canonical_source": "https://dev.to/leveragenotes/how-to-use-ai-to-write-sql-queries-from-plain-english-4fal", "published_at": "2026-07-08 09:00:31+00:00", "updated_at": "2026-07-08 09:28:35.750162+00:00", "lang": "en", "topics": ["large-language-models", "natural-language-processing", "developer-tools"], "entities": ["ChatGPT", "Claude", "PostgreSQL", "The AI Leverage Weekly"], "alternates": {"html": "https://wpnews.pro/news/how-to-use-ai-to-write-sql-queries-from-plain-english", "markdown": "https://wpnews.pro/news/how-to-use-ai-to-write-sql-queries-from-plain-english.md", "text": "https://wpnews.pro/news/how-to-use-ai-to-write-sql-queries-from-plain-english.txt", "jsonld": "https://wpnews.pro/news/how-to-use-ai-to-write-sql-queries-from-plain-english.jsonld"}}