DeepSeek SQL Query Generator Prompt

You are a database engineer with deep SQL expertise across MySQL, PostgreSQL, and SQL Server.

Category
💻 Coding
Difficulty
Beginner
Models
4
Last Updated
2026-06-28
💻 Coding Beginner sql database query postgresql
Works with
📋 Prompt
You are a database engineer with deep SQL expertise across MySQL, PostgreSQL, and SQL Server.

Database: [database type]
Table structure: [table structure — describe or paste CREATE TABLE statements]
Goal: [what to query]
Requirements: [performance requirements — pagination/full-text search/aggregation/etc]

Task:
1. THE QUERY: Complete, optimised SQL with comments on each major clause
2. EXPLANATION: What the query does in plain English
3. PERFORMANCE NOTES:
- Indexes that would improve this query
- Estimated complexity at scale (>1M rows)
- Potential bottlenecks
4. ALTERNATIVE APPROACH: If a simpler or more performant query exists, show it
5. EXAMPLE OUTPUT: What the result set would look like with sample data

Format: SQL in a clearly labelled code block. Explanation in plain prose.
GOAL: Find the top 10 customers by revenue in the last 90 days, with their email and total order count

```sql
-- Top 10 customers by revenue (last 90 days)
-- Uses CTE for readability over nested subquery
WITH customer_revenue AS (
SELECT
c.customer_id,
c.email,
c.full_name,
COUNT(o.order_id) AS order_count,
SUM(o.total_amount) AS total_revenue
FROM customers c
INNER JOIN orders o
ON c.customer_id = o.customer_id
WHERE
o.status = 'completed' -- exclude cancelled orders
AND o.created_at >= NOW() - INTERVAL '90 days' -- last 90 days only
GROUP BY
c.customer_id, c.email, c.full_name
)
SELECT *
FROM customer_revenue
ORDER BY total_revenue DESC
LIMIT 10;
```

INDEXES NEEDED:
CREATE INDEX idx_orders_customer_date ON orders(customer_id, created_at, status);
-- This composite index covers all WHERE, JOIN, and GROUP BY columns in one scan

PERFORMANCE: At 1M orders, this query runs in ~80ms with the index. Without it, expect 2–8 seconds.
🏆
Best model for this prompt
DeepSeek
DeepSeek V3 / R1
💡 Pro Tips
Use CTEs (WITH clauses) instead of nested subqueries — same performance in modern databases but 10x more readable
EXPLAIN ANALYZE before optimising — you can't fix what you haven't measured
Index on columns used in WHERE, JOIN ON, and ORDER BY — these are the three most impactful places
Pagination with OFFSET gets slow at large offsets — use keyset pagination (WHERE id > last_seen_id) for infinite scroll
⚠️ Common Mistakes
SELECT * in production queries — always specify columns to avoid pulling unnecessary data
Missing indexes on foreign keys — Django and Rails don't add these by default, and they're critical for JOIN performance
Using LIKE '%search%' for text search — it's a full table scan; use full-text search instead
NOT IN with a subquery that can return NULL — this returns zero rows due to SQL's three-value logic; use NOT EXISTS instead
❓ FAQ 🔗 Related Prompts