Coding
SQL Query Prompt: Write Complex Queries
This sql query prompt writes optimized queries from plain-English requests with explanations and indexes. Describe the tables, paste into any AI tool.
The prompt
Role: Act as a database engineer with 10 years of experience in query optimization. Context: Database: [DATABASE_TYPE]. Table schemas: [TABLE_SCHEMAS]. Request in plain English: [REQUEST]. Performance needs: [PERFORMANCE_NEEDS] (e.g., runs on 10M rows, must finish under 2s). Task: 1. Write the SQL query that fulfills [REQUEST]. 2. Explain the query logic step by step: joins, filters, aggregations. 3. Suggest indexes that speed it up, with CREATE INDEX statements. 4. Note edge cases: NULLs, duplicates, timezone handling. 5. Provide a simpler alternative if the request allows a trade-off. 6. Estimate the query plan shape (scan vs index seek) for the largest table. Format: - SQL (formatted code block) - Logic explained - Recommended indexes (code block) - Edge cases - Simpler alternative Constraints: - Use standard SQL compatible with [DATABASE_TYPE]; note dialect-specific functions. - Never use SELECT * in the final query. - Parameterize values; no hardcoded literals except in examples. - The query must be read-safe: no writes, no schema changes.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[DATABASE_TYPE] [TABLE_SCHEMAS] [REQUEST] [PERFORMANCE_NEEDS]
Example input
DATABASE_TYPE: PostgreSQL 16; TABLE_SCHEMAS: users(id, created_at), orders(id, user_id, total, status, created_at); REQUEST: monthly revenue per new vs returning customer for 2025; PERFORMANCE_NEEDS: 8M orders, under 3s
How to use this prompt
Copy the prompt. Paste table schemas and describe the request plainly. Run in any AI tool, then test on a staging database first.
Tips for the best results
- Tip: Always EXPLAIN the generated query before running it on large tables.
- Tip: Include row counts per table — the AI picks better join strategies with that context.
- Tip: Ask for the query with and without window functions to compare readability.
Frequently asked questions
Which SQL dialects are supported?
Any, when DATABASE_TYPE is specified. The prompt notes dialect-specific functions so the query stays portable.
Is AI-generated SQL safe to run?
Review every query and test on staging. AI can misread schema relationships, especially with ambiguous column names.