Best AI tools for writing SQL queries

Choose Copilot, Gemini in BigQuery or Cortex Analyst by environment. Check joins and totals with a SQL exercise executed on fictional data.

An analyst checks the results of a SQL query

For AI-assisted SQL, first choose a tool that fits your environment: GitHub Copilot in your code editor, Gemini in BigQuery for a BigQuery project, or Cortex Analyst when your data and business definitions live in Snowflake. Reliability does not come from the model's name. It must be checked against the schema, business rules and expected results.

Product documentation checked on 13 November 2026. We did not compare the tools' responses in a common account. However, the teaching query below was successfully executed in SQLite 3.53.1 using fictional data. That verifies the exercise, not product accuracy or automatic compatibility with every SQL dialect.

A query can run and still answer the wrong question

SQL is used to query tables. A join connects their rows, a filter selects which ones matter, and an aggregation calculates a total or count. A database may accept a query even though the result omits customers without orders or counts a sale twice.

Before asking for “this month's revenue”, define what belongs in the calculation: paid orders or issued invoices, order date or payment date, refunds, currency and timezone. If these choices are not explicit, the assistant may make them for you.

Three workflows, not a universal ranking

GitHub Copilot for a code project

GitHub Copilot documentation describes assistance with query generation in the editor. We would choose it when you already work with SQL files and a versioned schema. Make the schema and constraints available; do not assume the assistant knows the actual relationships between your tables.

Gemini in BigQuery for Google's warehouse

Gemini in BigQuery can help generate SQL from a natural-language request and schema, and explain or correct queries. We would consider it when the data is already in BigQuery. Integrated context is useful, but permissions and execution costs still require review.

Cortex Analyst for business definitions in Snowflake

Cortex Analyst uses semantic definitions to connect questions with Snowflake data. It merits consideration when several people need to query the same metrics using consistent definitions. Preparation matters: naming a column “revenue” does not fully define how revenue should be calculated.

The minimum brief for an assistant

  • The engine and dialect: SQLite, PostgreSQL, BigQuery or another, including the relevant version.
  • Actual tables, columns, types, keys and relationships.
  • The definition of each metric and the exact reporting period.
  • How to handle nulls, duplicates and missing rows.
  • A few fictional records with independently calculated expected results.
  • A read-only constraint and the parameters to use.

Do not send real customer records to explain a join when an invented example is sufficient. Even a schema can reveal internal organisation, so use an approved service for your context. Never paste a database password into a prompt.

Exercise: keep customers without paid orders

Our objective is precise: for each customer, count paid orders in October 2026 and sum their amounts in cents. Every customer must appear, even with zero. Dates are ten-character ISO strings in this exercise. There are no times, timezones or partial refunds.

The customers are Amina (1), Benoit (2), Carla (3) and Dina (4). The six orders are: Amina, 3 October, paid, 10,000 cents; Amina, 20 October, paid, 5,000; Amina, 21 October, cancelled, 7,000; Benoit, 15 October, cancelled, 8,000; Carla, 30 September, paid, 9,000; Carla, 1 November, paid, 11,000. Dina has no orders.

The schema is customers(id, name) and orders(id, customer_id, ordered_on, status, amount_cents). Each order identifier is unique, and one row represents an order, not a basket item. This is the reference query executed against the fictional dataset:

SELECT c.id, c.name,
       COUNT(o.id) AS paid_orders,
       COALESCE(SUM(o.amount_cents), 0) AS total_cents
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.id
 AND o.status = 'paid'
 AND o.ordered_on >= '2026-10-01'
 AND o.ordered_on < '2026-11-01'
GROUP BY c.id, c.name
ORDER BY c.id;

Verified result: Amina: 2 orders and 15,000 cents; Benoit: 0 and 0; Carla: 0 and 0; Dina: 0 and 0. The €150 total covers only Amina's two paid orders in the period. This is not a universal definition of accounting revenue.

Why the details of this query matter

LEFT JOIN preserves customers without a matching order. Order conditions belong in ON here to restrict matched rows without eliminating those customers. Moving the conditions naively into WHERE would remove zero-result customers.

COUNT(o.id) counts matched orders. Using COUNT(*) can count the row for a customer without orders when you expect zero. COALESCE converts an absent total into zero. Grouping includes the identifier so that two customers with the same name do not merge.

The exclusive end boundary excludes 1 November. For a real database with timestamps, adapt types, syntax and timezone explicitly. Do not copy this example's date strings into another platform without checking those differences.

A prompt to try

Write a SELECT query for this schema in SQLite. For every customer, count only paid orders from 1 October 2026 inclusive to 1 November exclusive and sum their cents. Keep customers without orders with zero values. Explain the join and counting logic. Execute nothing and propose no data changes. Flag any missing business rule.

Next, ask what would change if an order had several item rows. This is a useful reasoning check: joining those rows carelessly may multiply header-level amounts. The correction depends on the real schema, not a universal formula.

Before running against real data

  1. Have the query and referenced objects reviewed.
  2. Use a role restricted to reading only the necessary data.
  3. Test first in a demonstration environment or on an approved extract.
  4. Parameterise values from users rather than concatenating text.
  5. Inspect the execution plan or cost estimate available in your engine.
  6. Compare totals, row counts and edge cases against an independent reference.

A “read-only” prompt is not a security control. The account's permissions must enforce that boundary. Similarly, a row limit does not guarantee a cheap query: computation may scan substantial data before producing those rows.

Compare cost and usefulness

Separate assistant cost from database execution cost. Check your account's actual offers and limits rather than a generic price. Measure the time needed to obtain a reviewed query that passes your test cases. An instant response followed by an hour of repair is less useful than a cautious first suggestion.

Keep the question, schema version, query and expected results together. When a table changes, rerun the checks before trusting an old query. A renamed status or a new refund representation can invalidate a calculation even when its syntax still works.

Frequently asked questions

Do you need to be a developer?

You can express a question without being one, but somebody must be able to verify the logic and access controls before the result supports a decision. Start with fictional data whose answers you know.

Is a result without a technical error trustworthy?

Not automatically. The engine primarily validates execution, not your business intent. Missing customers, duplicates and boundary dates are exactly the cases to test.

Which should you start with?

Use a workflow compatible with your existing environment. For editor assistance, see the GitHub Copilot tool page. If your data is an Excel workbook rather than a SQL database, read our Excel and CSV analysis guide.

Reproduce our SQL exercise exactly

Save this script as exercise.sql, then run sqlite3 :memory: < exercise.sql with SQLite installed. It creates only an ephemeral database with four fictional customers and six orders. Do not run it on your production database.

CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, ordered_on TEXT NOT NULL, status TEXT NOT NULL, amount_cents INTEGER NOT NULL);
INSERT INTO customers VALUES (1,'Amina'),(2,'Benoit'),(3,'Carla'),(4,'Dina');
INSERT INTO orders VALUES
(101,1,'2026-10-03','paid',10000),
(102,1,'2026-10-20','paid',5000),
(103,1,'2026-10-21','cancelled',7000),
(104,2,'2026-10-15','cancelled',8000),
(105,3,'2026-09-30','paid',9000),
(106,3,'2026-11-01','paid',11000);
SELECT c.id, c.name,
       COUNT(o.id) AS paid_orders,
       COALESCE(SUM(o.amount_cents), 0) AS total_cents
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.id
 AND o.status = 'paid'
 AND o.ordered_on >= '2026-10-01'
 AND o.ordered_on < '2026-11-01'
GROUP BY c.id, c.name
ORDER BY c.id;

Expected result (ID, name, paid orders, total in cents):

1|Amina|2|15000
2|Benoit|0|0
3|Carla|0|0
4|Dina|0|0

We reran this fixture in memory using Python’s sqlite3 module. The command above runs the same script through the SQLite client. These results verify our example, not an AI vendor’s quality.

Related tools