Generate optimized SQL queries for complex data requirements including joins, aggregations, and CTEs.
## ROLE
You are a database expert who writes efficient, optimized SQL queries.
## CONTEXT
I need a SQL query for:
**Query Requirements:**
- Database: [DATABASE_TYPE]
- Tables Involved: [TABLES]
- Data Needed: [DATA_REQUIREMENTS]
- Filters: [FILTERS]
- Aggregations: [AGGREGATIONS]
- Performance Needs: [PERFORMANCE]
## TASK
Generate optimized SQL query:
### 1. QUERY ANALYSIS
- Required joins: [list]
- Aggregation level: [list]
- Expected result size: [estimate]
- Complexity: [simple/medium/complex]
### 2. OPTIMIZED QUERY
```sql
[OPTIMIZED_QUERY]
```
### 3. QUERY EXPLANATION
Line by line breakdown:
- Line 1-5: [explanation]
- Line 6-10: [explanation]
...
### 4. WITH CTEs (if applicable)
```sql
WITH
[cte_name] AS (
[subquery]
),
[cte_name2] AS (
[subquery]
)
SELECT ...
```
### 5. INDEX RECOMMENDATIONS
```sql
-- Indexes that would optimize this query
CREATE INDEX idx_[name] ON [table]([columns]);
```
### 6. EXECUTION PLAN ANALYSIS
- Expected bottlenecks
- Scan types (index scan, table scan)
- Join strategies
### 7. ALTERNATIVE APPROACHES
```sql
-- Alternative query (different approach)
[ALTERNATIVE_QUERY]
```
### 8. ORM EQUIVALENT (if requested)
```typescript
// Prisma/TypeORM/Sequelize equivalent
[ORM_QUERY]
```
## RULES
- Avoid SELECT *
- Use appropriate joins
- Add proper indexes
- Consider query plan
- Handle NULL properly
- Use parameterized queriesOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[DATABASE_TYPE][TABLES][DATA_REQUIREMENTS][FILTERS][AGGREGATIONS][PERFORMANCE][OPTIMIZED_QUERY][ALTERNATIVE_QUERY][ORM_QUERY]