SQL Query Builder

Builds optimized SQL queries with index recommendations, performance analysis, and alternative approaches for complex data requirements.

Coding & Development · intermediate · ChatGPT

Prompt template

Build an optimized SQL query for the following requirement.

Database: {{database_type}}
Tables involved: {{table_names_and_schemas}}
Requirement: {{what_data_to_retrieve_or_modify}}
Filters: {{filter_conditions}}
Sorting: {{sort_requirements}}
Pagination: {{yes_no_page_size}}

Please provide:
1. The optimized SQL query
2. Explanation of the query logic
3. Index recommendations for performance
4. Potential pitfalls (N+1 queries, full table scans)
5. Alternative approaches if applicable
6. Estimated performance characteristics

Example output

```sql
SELECT 
  u.name,
  COUNT(o.id) as order_count,
  SUM(o.total) as lifetime_value
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2025-01-01'
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 5
ORDER BY lifetime_value DESC
LIMIT 50 OFFSET 0;
```

Recommended index: `CREATE INDEX idx_orders_user_id_total ON orders(user_id, total);`

Use cases

  • Backend developers writing complex queries
  • Data analysts extracting business insights
  • Database administrators optimizing slow queries

Tags

SQL, database, query-optimization, performance