Asking AI to Generate SQL
AI is very capable of generating SQL queries from plain English descriptions. SQL generation prompts work best when you describe your database schema and the exact data you need.
10 min•By Priygop Team•Updated 2026
SQL Generation Prompt Template
SQL Generation Prompt Template
# SQL generation prompt template
sql_prompt = """
Write a SQL query for the following requirement.
Database: PostgreSQL (or MySQL / SQLite - specify yours)
Tables and columns:
- users (id, name, email, created_at, active)
- orders (id, user_id, product_name, amount, order_date)
Requirement:
Find all users who have placed more than 3 orders
in the last 30 days, sorted by the total order amount
(highest first). Show: user name, email, order count,
and total amount.
"""
# Why this prompt works:
# 1. Specifies the database type
# 2. Describes the exact table structure
# 3. States the requirement clearly
# 4. Defines the required output columns
# Bad SQL prompt:
bad_sql = "Write a SQL query to get users."
# AI does not know the tables, columns, or what you want.
print("Always include table names and columns in SQL prompts.")
print("Test all SQL on a development database before production.")Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
Key Takeaways
- SQL prompts must include table names, column names, and the database type
- Describe the exact data you need, not just the general topic
- Specify sort order, filters, and grouping requirements explicitly
- Always test AI-generated SQL on development data before running on production
- Review the query to make sure it matches your requirement before executing it
Key Takeaways
- AI is very capable of generating SQL queries from plain English descriptions.
- SQL prompts must include table names, column names, and the database type
- Describe the exact data you need, not just the general topic
- Specify sort order, filters, and grouping requirements explicitly