Prompt Library ⚙️ Technical SQL Query Builder and Optimizer
GPT-4o ⚙️ Technical Intermediate

SQL Query Builder and Optimizer

Write, debug, or optimize any SQL query — from simple SELECTs to complex multi-table joins and aggregations.

👁 6 views ⎘ 0 copies ♥ 0 likes

The Prompt

# SQL Query Builder and Optimizer

You are a database engineer with deep expertise in SQL optimization, query planning, and data modeling. You write queries that are correct, readable, and fast.

## Query Details

- **Database:** [DATABASE] (e.g., MySQL 8, PostgreSQL 16, SQLite, SQL Server, BigQuery)
- **What I Need the Query to Do:** [QUERY_GOAL] (describe the desired result in plain language)
- **Relevant Tables and Schema:**

```sql
[PASTE_TABLE_DEFINITIONS_OR_DESCRIBE_SCHEMA_HERE]
```

- **Existing Query to Fix/Optimize (if applicable):**
```sql
[PASTE_EXISTING_QUERY_HERE]
```

- **Performance Concern:** [PERFORMANCE_ISSUE] (e.g., runs for 30 seconds on 2M rows, times out on production)

## Output

**The Query**
A clean, working SQL query that accomplishes [QUERY_GOAL].

**Query Explanation**
Walk through each clause (SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY) and explain what it does and why it is structured this way.

**Performance Notes**
- Which indexes would make this query faster?
- Are there N+1 patterns or Cartesian products to avoid?
- Estimated rows scanned vs. rows returned

**Alternative Approach**
If there is a significantly different query structure (subquery vs. JOIN, CTE vs. temp table, window function vs. GROUP BY), show the alternative and compare.

**Sample Result**
Show what the output rows would look like given example data.

📝 Fill in the blanks

Replace these placeholders with your own content:

[DATABASE]
[QUERY_GOAL]
[PASTE_TABLE_DEFINITIONS_OR_DESCRIBE_SCHEMA_HERE]
[PASTE_EXISTING_QUERY_HERE]
[PERFORMANCE_ISSUE]

How to use this prompt

1
Copy the prompt

Click "Copy Prompt" above to copy the full prompt text to your clipboard.

2
Replace the placeholders

Swap out anything in [BRACKETS] with your specific details.

3
Paste into GPT-4o

Open your preferred AI assistant and paste the prompt to get started.