🗄️ SQL & Database — Hands-On Test

Can AI Write SQL Queries? I Tested It on a Real PostgreSQL Database (2026)

📅 July 2026⏱️ 10 min read✍️ 🔄 Updated Jul 2026

Our Verdict — July 2026

AI writes production-quality SQL for well-defined questions — JOINs, aggregations, even window functions. But it fails in the most dangerous way possible: queries that run without errors and return the wrong data. Use it to write faster; never skip the review.

3.5/5
prompts passed cleanly
★★★★☆

Every "AI can write SQL" article shows the same demo: a toy question, a perfect query, applause. That's not how databases work in real life. Real schemas have misleading column names, NULLs where you least expect them, and duplicate rows that quietly double your revenue numbers. So we built a realistic PostgreSQL schema — the kind you'd find behind any e-commerce or booking system — and ran 5 prompts of increasing difficulty through three tools: ChatGPT, AI2SQL and GitHub Copilot. Same schema, same prompts. Here's exactly what happened, including the failure that would have shipped wrong numbers to a dashboard.

⚡ Short Answer Yes, AI can write real SQL — 3 of our 5 test prompts passed on the first try, including a window-function query. But one query was silently wrong (it ran fine and returned bad data), which is exactly why AI SQL needs the same review you'd give a junior developer's code.
5
Prompts tested, from simple filter to messy business logic
3
Passed first try with zero edits needed
1
Silently wrong — ran fine, returned bad data

🗄️ The Test Schema

Four tables, deliberately imperfect — including a trap: orders.status uses text values and cancelled orders still have rows in order_items. Just like real production data.

CREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, full_name TEXT, country TEXT, created_at TIMESTAMP ); CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, customer_id INT REFERENCES customers(customer_id), order_date DATE, status TEXT -- 'completed', 'cancelled', 'refunded', 'pending' ); CREATE TABLE order_items ( item_id SERIAL PRIMARY KEY, order_id INT REFERENCES orders(order_id), product_id INT, quantity INT, unit_price NUMERIC(10,2) -- price at time of sale ); CREATE TABLE products ( product_id SERIAL PRIMARY KEY, product_name TEXT, category TEXT, list_price NUMERIC(10,2) -- current price (the trap!) );

Test 1 — Simple filter

✅ ALL 3 PASSED
-- Prompt: "Customers from India who signed up in the last 90 days" SELECT customer_id, full_name, created_at FROM customers WHERE country = 'India' AND created_at >= CURRENT_DATE - INTERVAL '90 days';
No surprises. Every tool produced a correct query instantly. If your needs stop at filters and sorting, AI already replaces the SQL cheat-sheet tab you keep open.

Test 2 — JOIN + aggregation

✅ ALL 3 PASSED
-- Prompt: "Total revenue per product category from completed orders in 2026" SELECT p.category, SUM(oi.quantity * oi.unit_price) AS total_revenue FROM order_items oi JOIN orders o ON o.order_id = oi.order_id JOIN products p ON p.product_id = oi.product_id WHERE o.status = 'completed' AND o.order_date >= '2026-01-01' GROUP BY p.category ORDER BY total_revenue DESC;
Impressive detail: all three tools correctly filtered status = 'completed' without being told cancelled orders existed — the word "completed" in the prompt was enough. ChatGPT even added a comment explaining the JOIN order.

Test 3 — Window function

✅ 2 PASSED, 1 NEEDED A FIX
-- Prompt: "Each customer's orders with a running total of their spend over time" SELECT o.customer_id, o.order_id, o.order_date, SUM(oi.quantity * oi.unit_price) AS order_value, SUM(SUM(oi.quantity * oi.unit_price)) OVER ( PARTITION BY o.customer_id ORDER BY o.order_date, o.order_id ) AS running_total FROM orders o JOIN order_items oi ON oi.order_id = o.order_id WHERE o.status = 'completed' GROUP BY o.customer_id, o.order_id, o.order_date;
The nested SUM(SUM(...)) OVER pattern trips up plenty of humans — two tools got it right first try. Copilot's first attempt put the window function in a WHERE clause (invalid SQL); asking it to fix the error produced the correct version. Verdict: AI handles window functions better than most mid-level developers expect.

Test 4 — The column-name trap

⚠️ 2 OF 3 FELL FOR IT
-- Prompt: "Total value of products sold per category this year" -- WRONG (2 of 3 tools): used current list_price, not the sale price SELECT p.category, SUM(oi.quantity * p.list_price) AS total_value -- ❌ trap! FROM order_items oi JOIN products p ON p.product_id = oi.product_id ...
This is the failure mode to fear. The schema has two prices: unit_price (what the customer actually paid) and list_price (today's catalog price). Two tools grabbed list_price — the query runs perfectly, the numbers look plausible, and every historical discount or price change silently corrupts the result. Only the tool that read the column comments chose correctly. If your schema has ambiguous names, AI will guess — and it guesses confidently.

Test 5 — Messy business logic

❌ ALL 3 NEEDED HUMAN CORRECTION
-- Prompt: "Monthly net revenue for 2026, where refunded orders count as negative" -- Every tool's first attempt either ignored refunds or double-counted them. -- Correct version required spelling out the logic explicitly: SELECT DATE_TRUNC('month', o.order_date) AS month, SUM( CASE WHEN o.status = 'completed' THEN oi.quantity * oi.unit_price WHEN o.status = 'refunded' THEN -(oi.quantity * oi.unit_price) ELSE 0 END ) AS net_revenue FROM orders o JOIN order_items oi ON oi.order_id = o.order_id WHERE o.order_date >= '2026-01-01' GROUP BY 1 ORDER BY 1;
"Net revenue" means something specific to your business, and no AI knows your definition until you state it. Once we rewrote the prompt with explicit rules ("completed counts positive, refunded counts negative, ignore pending and cancelled"), every tool produced the correct query. Lesson: AI is only as good as the business logic you spell out. Vague prompt in, plausible-looking nonsense out.
⚠️ Before You Run AI SQL on Anything Real Treat AI-generated SQL like a pull request from a new team member: read every line, test against results you already know are correct, run EXPLAIN before hitting large tables, and never execute an AI-written UPDATE or DELETE without checking the WHERE clause inside a transaction you can roll back. The dangerous failures in our test weren't syntax errors — they were queries that ran successfully and returned wrong numbers. A dashboard doesn't know the difference.

⚔️ Which Tool Did Best?

TestChatGPTAI2SQLGitHub Copilot
1. Simple filterPassPassPass
2. JOIN + aggregationPassPassPass
3. Window functionPassPassFixed after error
4. Column-name trapFell for itFell for itRead the comments
5. Messy business logicNeeded rewriteNeeded rewriteNeeded rewrite
Best at explaining itselfBestBasicGood

Takeaway: Copilot won the trap test because it reads your open files — schema comments included. That's a structural advantage: the more context a tool can see, the fewer confident guesses it makes. ChatGPT was the best teacher, explaining why each query works. AI2SQL was the fastest from plain English to runnable query, ideal when you know your schema well and just want speed.

🎯 How to Actually Use AI for SQL

✅ Do this:
→ Paste your schema (with column comments!) before asking for any query
→ Spell out business rules explicitly — "refunded counts negative, ignore pending"
→ Ask the AI to explain its query back to you — mismatches reveal wrong assumptions fast
→ Use it for the 80%: boilerplate JOINs, date logic, window function syntax you always forget
→ Validate against a known-correct result before trusting a new query
⚠️ Don't do this:
→ Run AI-generated UPDATE/DELETE statements without reviewing the WHERE clause
→ Trust results just because the query executed without errors
→ Paste production schemas or sample rows into AI tools without checking your company's data policy
→ Ask vague questions about metrics with ambiguous definitions — define them first
✅ Where AI SQL Shines
✓ Syntax you rarely use — window functions, CTEs, pivots
✓ Translating requirements into first-draft queries in seconds
✓ Explaining inherited legacy queries line by line
✓ Dialect conversion — PostgreSQL to Redshift, MySQL to BigQuery
✓ Debugging error messages faster than Stack Overflow
⚠️ Where It Still Fails
✗ Ambiguous column names — it guesses confidently
✗ Unstated business logic — your definitions aren't in its head
✗ Silent correctness bugs that no error message will catch
✗ Query performance — rarely considers indexes unless asked
✗ Edge cases: NULLs, duplicates, timezone boundaries

❓ FAQs

Can AI write SQL queries accurately?
Yes — for well-defined tasks against a schema it can see, modern AI writes correct SQL most of the time, including JOINs, aggregations and window functions. Accuracy drops sharply when the schema is ambiguous, when column names are misleading, or when business logic has unstated rules and edge cases. In our 5-prompt PostgreSQL test, AI passed 3 cleanly, needed a fix on 1, and produced a silently wrong result on 1.
What is the best AI tool for writing SQL in 2026?
It depends on where you work. For plain-English-to-query speed, AI2SQL is the fastest and supports 10+ database dialects. Inside your IDE, GitHub Copilot is strongest because it reads your open schema files — which is exactly why it dodged our column-name trap. ChatGPT is the best explainer and debugger. Many developers run Copilot in the editor and keep ChatGPT open for debugging sessions.
Is it safe to run AI-generated SQL in production?
Not without review. Treat it like code from a junior developer: read it, test against known results, run EXPLAIN on large tables, and never execute AI-generated UPDATE or DELETE statements without reviewing the WHERE clause inside a transaction you can roll back. The biggest risk is not syntax errors — it's queries that run successfully and return subtly wrong data.
Can ChatGPT connect to my PostgreSQL database?
Not directly in the standard chat interface — you paste your schema and run the queries yourself. Tools like Chat2DB connect live to your database and let AI query it with natural language. For production or sensitive data, check your company's data policy before pasting schemas or sample rows into any external AI tool.

🗄️ Write SQL Faster — With Your Eyes Open

Compare the AI SQL tools we tested, plus the full IT & Data toolkit in our directory.

Vivek Shinde
Founder & Reviewer, ToolPikr

IT professional working day to day with PostgreSQL, Amazon Redshift and production ETL pipelines. Every tool on ToolPikr is tested by hand before it gets recommended. More about how we test →