Back to prompts
Data & Analysisintermediate
4.8

SQL Query Builder — Write Complex Queries by Describing What You Want

Describe your data question in plain English and get optimized SQL with explanation — from simple SELECTs to complex JOINs, CTEs, and window functions.

Copy & Paste this prompt
You are a senior database engineer. Help me build the query I need.

My Database:
- Database type: [PostgreSQL / MySQL / SQL Server / SQLite / BigQuery]
- Tables involved: [DESCRIBE]
- What I want to find: [PLAIN ENGLISH]

Provide:
1. THE QUERY (formatted SQL)
2. LINE-BY-LINE EXPLANATION
3. PERFORMANCE NOTES (indexes, optimization)
4. VARIATIONS (add filters, group differently)
5. COMMON PITFALLS (NULLs, timezones, duplicates)
6. OPTIMIZATION (CTE vs subquery vs temp table)

Write clean, readable SQL. Use CTEs for complex queries.
#SQL#database#queries#data-analysis#programming

Works with

chatgptclaudeany

💡 Pro Tips

  • Always specify your database type — syntax varies
  • Ask follow-up: 'Add month-over-month trend column'
  • Use CTEs for readability

✨ Example Output

📋 REQUEST: 'Top 10 premium customers by spending, last 90 days, 3+ orders'

```sql
WITH customer_stats AS (
  SELECT u.id, u.name, u.email,
    COUNT(o.id) AS order_count,
    SUM(o.amount) AS total_spent
  FROM users u
  JOIN orders o ON o.user_id = u.id
  WHERE u.plan_type = 'premium'
    AND o.status = 'completed'
    AND o.created_at >= CURRENT_DATE - INTERVAL '90 days'
  GROUP BY u.id, u.name, u.email
  HAVING COUNT(o.id) >= 3
)
SELECT * FROM customer_stats
ORDER BY total_spent DESC LIMIT 10;
```

🧠 Why This Works

SQL syntax for complex queries is hard to remember. This prompt lets you describe your question naturally and get optimized SQL with explanations and performance notes.

📅 When to Use This Prompt

When you know what data you want but can't figure out the SQL, when optimizing slow queries, or when building reports.

🎯 What You'll Get

A working SQL query with explanation, performance tips, and variations.

🔗 Related Prompts