SQL with AI
Jump to section
SQL without memorizing syntax
SQL is the language for working with databases and is the foundation of analytical work. The problem is that learning SQL syntax takes months, and even experienced analysts search for the right way to write a complex query. AI changes this — describe what you want to know, and AI writes the SQL for you.
You do not need to know SQL to ask AI for a SQL query. You just need to know what data you have (which tables, which columns) and what you want to find out. AI handles the syntax, joins, aggregations and everything else.
How to describe a data request
For AI to generate correct SQL, it needs three things: the structure of your database (what tables and columns you have), what you want to find out (your business requirement), and what filters or conditions you want to apply.
Prompt for SQL: 'I have a table called orders with columns: id, customer_id, product_id, amount, created_at. And a table called customers with columns: id, name, email, country. Write a SQL query that shows the top 10 customers by total amount spent in the last 12 months, including name and order count.'
-- AI generates something like:
SELECT
c.name,
c.email,
COUNT(o.id) AS order_count,
SUM(o.amount) AS total_spent
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY c.id, c.name, c.email
ORDER BY total_spent DESC
LIMIT 10;Core SQL patterns
There are several SQL patterns that cover 90% of use cases. You do not need to memorize them — just knowing they exist helps you formulate better requests to AI. But understanding them helps you validate the results.
Filtering and sorting
-- 'Show orders over $100 from the last month,
-- sorted by newest first'
SELECT *
FROM orders
WHERE amount > 100
AND created_at >= CURRENT_DATE - INTERVAL '1 month'
ORDER BY created_at DESC;Aggregations (sums, averages, counts)
-- 'How many orders and how much revenue did we have
-- each month in 2025?'
SELECT
DATE_TRUNC('month', created_at) AS month,
COUNT(*) AS order_count,
SUM(amount) AS total_revenue,
AVG(amount) AS avg_order_value
FROM orders
WHERE created_at >= '2025-01-01'
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY month;Joins (combining tables)
-- 'For each product show the name, category,
-- total sales and number of customers'
SELECT
p.name AS product_name,
p.category,
SUM(o.amount) AS total_sales,
COUNT(DISTINCT o.customer_id) AS unique_customers
FROM orders o
JOIN products p ON o.product_id = p.id
GROUP BY p.id, p.name, p.category
ORDER BY total_sales DESC;Window functions
Window functions are an advanced SQL concept that AI handles flawlessly. They are used for calculations 'within a group' — for example, comparing each customer to the average of their region.
-- 'For each customer show their monthly spending
-- and the average for their region in the same month'
SELECT
c.name,
c.country,
DATE_TRUNC('month', o.created_at) AS month,
SUM(o.amount) AS customer_spending,
AVG(SUM(o.amount)) OVER (
PARTITION BY c.country,
DATE_TRUNC('month', o.created_at)
) AS region_avg
FROM orders o
JOIN customers c ON o.customer_id = c.id
GROUP BY c.id, c.name, c.country,
DATE_TRUNC('month', o.created_at)
ORDER BY month, c.country;Validating AI-generated SQL
AI generates SQL that is mostly correct, but not always. Before running on production, you should check every query. There are simple rules that help.
- Check table and column names — AI sometimes invents them if it does not know the exact schema
- Verify JOIN conditions — a bad JOIN can multiply rows and distort results
- Test on a small dataset — add LIMIT 10 before running on the full database
- Ask AI to explain — 'Explain step by step what this query does'
- Compare with expected results — if you know the approximate answer, verify it
Golden rule: never run AI-generated queries with DELETE, UPDATE or DROP on a production database without review. For analytical SELECT queries the risk is low, but modification queries can cause irreversible damage.
Advanced techniques
Once you get comfortable with the basic patterns, you can ask AI for more complex analyses. Just describe the business question and AI combines joins, subqueries, window functions and CTEs into a single query.
Prompt for complex query: 'I have tables orders, customers and products. I want to see: for each product category the monthly revenue, month-over-month growth percentage, and cumulative revenue since the start of the year. Include only customers who have more than 3 orders.'
-- AI generates CTEs + window functions:
WITH active_customers AS (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 3
),
monthly_sales AS (
SELECT
p.category,
DATE_TRUNC('month', o.created_at) AS month,
SUM(o.amount) AS revenue
FROM orders o
JOIN products p ON o.product_id = p.id
WHERE o.customer_id IN (
SELECT customer_id FROM active_customers
)
AND o.created_at >= DATE_TRUNC('year', CURRENT_DATE)
GROUP BY p.category, DATE_TRUNC('month', o.created_at)
)
SELECT
category,
month,
revenue,
ROUND(
(revenue - LAG(revenue) OVER (
PARTITION BY category ORDER BY month
)) * 100.0 / NULLIF(LAG(revenue) OVER (
PARTITION BY category ORDER BY month
), 0), 1
) AS growth_pct,
SUM(revenue) OVER (
PARTITION BY category
ORDER BY month
) AS ytd_revenue
FROM monthly_sales
ORDER BY category, month;Describe one of these situations (or your own) to AI and have it generate SQL: 1. 'I have an e-shop with tables orders, customers and products. I want to see the top 5 customers who spent the most in the last quarter, including their favorite product category.' 2. 'I have a table events with columns user_id, event_type, created_at. I want to see the daily count of unique users who performed at least one action of type purchase.' 3. 'I have a table employees with columns name, department, salary, hire_date. I want a comparison of average salary by department and how many people are below and above the average in each department.' For each query, ask AI to explain what each part does.
Hint
If you have access to a database, try running the query. If not, ask AI to create test data (CREATE TABLE + INSERT INTO) and run the query in an online SQL editor like db-fiddle.com.
- AI generates SQL from natural language descriptions — you do not need to know the syntax
- Describe your database structure (tables, columns) and business requirement to AI
- Core patterns: filtering, aggregations, joins, window functions cover 90% of needs
- Always validate SQL before running — check names, JOIN conditions, test on small datasets
- Never run DELETE/UPDATE/DROP from AI without thorough review
In the next lesson, we dive into AI for Spreadsheets — a technique that gives you a clear edge. Unlock the full course and continue now.
2/7 complete — keep going!