Coding
AI Prompt for Explaining SQL Queries
Understand complex SQL with this AI prompt: plain-English clause breakdown, execution order, and a mental model for window functions, CTEs and joins.
The prompt
Role: You are a SQL teacher who turns intimidating queries into clear mental models. Context: Dialect: [DIALECT]. My level: [YOUR_LEVEL]. I roughly think this query does [YOUR_GUESS]. Query: [SQL_QUERY] Task: 1) Say in one sentence what the query returns. 2) Explain the logical execution order (FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY) as it applies to THIS query — most confusion comes from reading order vs execution order. 3) Walk through each clause: what it does and why it is needed here. 4) Demystify the advanced parts ([ADVANCED_PARTS, e.g. window functions, CTEs]) with a small data example traced step by step. 5) Give me one simpler query that captures the core idea. Format: One-sentence summary, then execution order, then clause walkthrough, then the traced example, then the simplified version. Constraints: Teach with MY query, not textbook examples. Correct [YOUR_GUESS] explicitly if it is wrong — do not let misconceptions stand.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[DIALECT] [YOUR_LEVEL] [YOUR_GUESS] [SQL_QUERY] [ADVANCED_PARTS]
Example input
DIALECT=PostgreSQL, QUERY=CTE with ROW_NUMBER() partitioned by customer, LEVEL=intermediate, GOAL=understand window functions
How to use this prompt
State what you already suspect the query does — the explanation corrects and deepens rather than starting cold. Ask about one confusing clause specifically for the deepest insight.
Tips for the best results
- Ask for the execution order first — it resolves most 'why does this work' confusion.
- Have it trace the query on 5 sample rows you provide.
- Request the 'one simpler query' version to isolate the concept you are learning.
Frequently asked questions
Can this teach me SQL concepts?
Yes — name the concept (window functions, CTEs, lateral joins) and it will teach through your actual query.
Why does the execution order differ from the written order?
SQL describes WHAT you want, and the engine decides HOW. FROM and WHERE logically run before SELECT, which is why you cannot use a SELECT alias in WHERE.