MagicTools
ai-promptsApril 22, 20261 views3 min read

ChatGPT Prompts for SQL Query Generation (2025)

ChatGPT Prompts for SQL Query Generation (2025)

Writing SQL is not that hard. Writing it correctly, quickly, and without Googling the same JOIN syntax for the fifth time — that's where ChatGPT actually earns its keep.

Here's how to use it well.


1. Basic SELECT + Filtering

Start simple. You have a users table and you want everyone who signed up in 2024 and is still active.

Prompt:

I have a table called `users` with columns: id, name, email, created_at, status.
Write a SQL query to get all users who signed up in 2024 and have status = 'active'.
Sort by created_at descending.

Result:

SELECT id, name, email, created_at
FROM users
WHERE YEAR(created_at) = 2024
  AND status = 'active'
ORDER BY created_at DESC;

2. JOIN Queries Across Multiple Tables

Prompt:

I have two tables:
- customers(id, name, email, city)
- orders(id, customer_id, total_amount, order_date, status)

Write a query to list all orders with the customer name and email.
Only include orders with status = 'completed'.

Result:

SELECT o.id AS order_id,
       c.name AS customer_name,
       c.email,
       o.total_amount,
       o.order_date
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'completed';

If you need a LEFT JOIN instead, just tell ChatGPT. It adjusts without drama.


3. GROUP BY + Aggregation

Prompt:

I have a table `sales` with columns: id, product_id, category, amount, sale_date.
Write a SQL query to get the total sales amount per category for Q1 2025.
Sort by total amount descending.

Result:

SELECT category,
       SUM(amount) AS total_amount
FROM sales
WHERE sale_date BETWEEN '2025-01-01' AND '2025-03-31'
GROUP BY category
ORDER BY total_amount DESC;

4. Subqueries and CTEs

Prompt:

Using a CTE, write a SQL query to find all customers whose total spending is above the average order total.
Tables:
- customers(id, name, email)
- orders(id, customer_id, total_amount)

Result:

WITH customer_totals AS (
    SELECT customer_id,
           SUM(total_amount) AS total_spent
    FROM orders
    GROUP BY customer_id
),
avg_spending AS (
    SELECT AVG(total_spent) AS avg_total
    FROM customer_totals
)
SELECT c.name, c.email, ct.total_spent
FROM customers c
JOIN customer_totals ct ON c.id = ct.customer_id
JOIN avg_spending av ON ct.total_spent > av.avg_total
ORDER BY ct.total_spent DESC;

Ready-to-Copy Prompt Templates

I have a table `[table_name]` with columns: [list columns].
Write a SQL query to [describe what you want].
Use [MySQL / PostgreSQL / SQLite] syntax.
Write a SQL JOIN query using these two tables:
- [table1]: [columns]
- [table2]: [columns]
Goal: [what data you need]
Filter: [any WHERE conditions]
Using a CTE, write a SQL query to [describe the goal].
Tables involved: [list tables and their key columns]
Explain each CTE step briefly in comments.

FAQ

Can ChatGPT write SQL for any database?

Yes, but you have to tell it which one. MySQL uses YEAR(date) while PostgreSQL prefers EXTRACT(YEAR FROM date). Just add "Use PostgreSQL syntax" or "Use MySQL syntax" to your prompt and it will adapt.

What if ChatGPT generates a query that doesn't work?

Paste the error message back into the chat. ChatGPT is usually good at diagnosing syntax errors, missing aliases, or wrong column names — especially if you give it the actual error output.

Is ChatGPT good enough to replace knowing SQL?

Not really. You still need to understand what JOIN types mean, when GROUP BY makes sense, and how to read a query result. ChatGPT speeds up writing, but if you can't read the output, you won't catch when it's wrong.

Can I ask ChatGPT to optimize an existing slow query?

Yes. Paste your current query and say "this is running slowly, how can I optimize it?" It will often suggest adding indexes, rewriting subqueries as JOINs, or removing unnecessary SELECT *.


Once you have your SQL from ChatGPT, run it through MagicTools SQL Formatter to clean it up instantly. Readable SQL is easier to debug, easier to share, and easier to maintain.

Related Articles

Tmux Terminal Multiplexer: Recommended Configuration + Complete User Manual

A complete guide to the tmux terminal multiplexer for developers, including recommended .tmux.conf configuration, common shortcut key cheat sheets, plugin recommendations, and practical tips to help you significantly improve terminal efficiency.

developerApr 22, 20267 min
11

Practical Guide to Document Format Conversion: Comprehensive Analysis of Markdown, HTML, PDF Interconversion

Comprehensive analysis of conversion methods for four major document formats: Markdown, HTML, PDF, and Word, comparing the pros and cons of various conversion tools, with practical steps and solutions to common problems, helping you choose the most suitable conversion path for different scenarios.

documentApr 22, 20268 min
10

Complete Guide to JWT Authentication: Principles, Usage, and Security Best Practices

JWT (JSON Web Token) is a mainstream solution for modern API authentication. This article provides an in-depth analysis of JWT's three-part structure, signature verification principles, comparison with Session, as well as key security practices such as storage location selection, expiration and refresh mechanisms, and algorithm confusion vulnerabilities.

developerApr 22, 20268 min
14

Complete Guide to Password Security: Best Practices from Creation to Management

Every year, billions of accounts are stolen due to weak passwords or password reuse. This article systematically explains common password attack methods, password strength standards, password manager selection, and the correct use of two-factor authentication, helping you fundamentally protect your digital asset security.

utilityApr 22, 20267 min
15

Published by MagicTools