· 9 min read
ChatGPT prompts for coding: debugging, code review and refactoring
Copy-ready ChatGPT prompts for coding: debugging, code review, refactoring, tests, SQL and regex, plus the context to include and the safety rules to follow.
The best ChatGPT prompts for coding are not clever phrases. They read like good bug reports: your stack and versions, the exact error, what you expected, what you already tried, and the smallest piece of code that reproduces the problem. Below you'll find a context checklist, a worked debugging example, and copyable templates for debugging, code review, refactoring, tests, unfamiliar code, SQL, regex and documentation. They work the same way in Claude, Gemini or Copilot Chat.
Give the model the context a senior developer would ask for
When you ask a colleague for help, they ask questions before reading a single line. A model rarely asks unless you invite it to, so it guesses. Answer those questions up front:
- Stack and versions. Language, framework, runtime and the libraries involved, with version numbers. "Python 3.12 with Django 5.1" gets different advice than "Python".
- The exact error. Paste the full message and stack trace, not your paraphrase. Line numbers and frame order carry the diagnosis.
- Expected vs actual behavior. One sentence each.
- What you already tried. This stops the model from suggesting the three fixes you ruled out an hour ago.
- A minimal reproduction. The smallest snippet that still fails. Cutting it down often reveals the bug before you even send the prompt.
- Constraints. "No new dependencies", "must stay compatible with Python 3.9", "runs in a serverless function with 512 MB".
- The output you want. A diagnosis first, a patch, a full file, or a list of hypotheses.
If the code depends on a type, schema or config that isn't in the snippet, include it or describe it. Models fill gaps with plausible inventions, and an invented field name looks exactly like a real one. For the general version of this structure, see how to write better ChatGPT prompts.
Debugging prompts: a before and after
Here's a classic bug. A developer at a small invoicing startup, Ledgerly, has this function in their React dashboard, and it always returns an empty array:
async function loadInvoices(ids) {
const invoices = [];
ids.forEach(async (id) => {
const res = await fetch(`/api/invoices/${id}`);
invoices.push(await res.json());
});
return invoices; // always []
}Before:
Why doesn't this work? [pastes code]
With a snippet this short, the model may spot the issue anyway. In a real codebase, though, this prompt produces generic advice ("check your endpoint", "add console.log") because there's no symptom, no evidence and no environment.
After:
I'm debugging a React 18 dashboard built with Vite. loadInvoices(ids) should return an array of invoice objects, but it always returns [] even though the network tab shows every request succeeding with a 200. Code: [paste the function] What I tried: logging inside the callback shows each invoice arriving, but only after the function has already returned. 1. Explain the root cause in two or three sentences. 2. Give a corrected version that keeps the requests parallel. 3. Add error handling so a failed request reports which id failed. Don't change the function signature.
Why it works: the symptom, the evidence ("arriving after the function returned") and the constraints point straight at the cause. forEach doesn't wait for async callbacks, so the function returns before any push runs. A good answer looks like this:
async function loadInvoices(ids) {
return Promise.all(
ids.map(async (id) => {
const res = await fetch(`/api/invoices/${id}`);
if (!res.ok) throw new Error(`Invoice ${id}: HTTP ${res.status}`);
return res.json();
}),
);
}Here's the reusable version:
Context: [language + version], [framework + version], running on [environment]. Goal: [what the code should do]. Actual behavior: [what happens instead]. Full error and stack trace: [paste] Minimal code that reproduces it: [paste] What I already tried: [list]. Constraints: [no new dependencies / must support X / can't change the API]. Before proposing a fix, list your top 3 hypotheses ranked by likelihood and the evidence that would confirm each. Then fix the most likely one. If you need information I haven't given you, ask instead of guessing.
Ranking hypotheses pays off when the bug isn't obvious: you get something to check, rather than a confident patch for the wrong cause.
Code review prompts that find real problems
"Review this code" gets you a polite list of style nits. Tell the model what kind of reviewer to be and what to ignore.
Before:
Can you review this code?
After:
Act as a senior [language] reviewer on a team that values correctness over cleverness. Review the diff below for: 1. Bugs and unhandled edge cases (empty input, nulls, concurrency, time zones). 2. Security issues (injection, missing authorization checks, secrets in code). 3. Performance problems that matter at [expected scale, e.g. 50,000 rows]. Ignore formatting and naming unless they cause confusion; our linter handles style. For each finding give: severity (high, medium, low), the line, why it's a problem, and a suggested fix. If you find nothing serious, say so instead of inventing issues. [paste diff]
Why it works: a defined scope, an explicit ignore list and a structured output. The last instruction matters most. Asking a model to find problems invites it to produce some, so give it permission to report a clean result. If you review this way every week, save the reviewer description as a custom instruction or system prompt; these system prompt examples show how.
Refactoring prompts that don't break behavior
The risk with AI refactoring is silent behavior change. Make "same behavior" the main constraint and ask for the plan before the code.
Refactor the function below for readability and testability. Rules: - Behavior must stay identical for all inputs, including the errors it throws. - Keep the public signature and return type. - No new dependencies. - Prefer small pure functions over classes. First, list the changes you plan and any behavior that could accidentally change. Then show the refactored code. Finally, list the test cases I should run to confirm nothing changed. [paste code]
Asking for a plan first lets you veto a bad direction before reading 200 lines of rewritten code. For bigger refactors, go one function or module at a time. A model asked to rewrite a whole file at once tends to drop edge-case handling quietly, and you won't notice until production does.
Prompts for tests, unfamiliar code and documentation
Writing tests:
Write [pytest / Jest / JUnit] tests for the function below. Cover: the happy path, boundary values, invalid input, and [domain-specific case, e.g. leap years, an empty cart]. Follow the style of the existing test file I've pasted below it (same fixtures, same mocking approach). Name each test after the behavior it checks. Don't test private helpers directly. After the tests, list any behavior you found ambiguous so I can decide what's correct. [paste function] [paste one existing test file]
Pasting one existing test file is the fastest way to get tests that match your conventions. It's few-shot prompting applied to code: one good example beats a paragraph of style rules.
Explaining unfamiliar code:
I'm a [your level, e.g. mid-level Python developer new to Go]. Explain the code below. 1. A two-sentence summary of what it does and why it probably exists. 2. A step-by-step walkthrough of the control flow. 3. Any non-obvious language features or patterns, with a one-line explanation each. 4. Anything that looks risky or surprising. Don't rewrite it. [paste code]
Documentation:
Write a [Google-style / NumPy-style / JSDoc] docstring for each public function below. Include parameters, return value, raised errors and one short usage example. Describe only what the code actually does; if something is unclear, add a TODO instead of guessing. [paste code]
That "don't guess" line keeps the docs honest. Documentation that confidently describes behavior the code doesn't have is worse than no documentation.
SQL and regex prompts
SQL and regular expressions are where vague prompts fail hardest, because the model has to guess your schema or your edge cases.
SQL, before:
Write a query to get our top customers.
SQL, after:
Database: PostgreSQL 16. Tables: - customers(id, name, created_at) - orders(id, customer_id, total_cents, status, created_at) Write a query that returns the 20 customers with the highest total spend in the last 90 days, counting only orders where status = 'paid'. Return customer id, name, order count and total spend in dollars, sorted by total spend descending. Then suggest any index that would speed it up.
Why it works: real table and column names, a precise definition of "top", a time window and the exact output columns. Without the schema, the model invents something like customers.total_spent, and the query either fails or runs against the wrong column.
Regex:
Write a regular expression for [JavaScript / Python re / PCRE] that matches [description]. Must match: [3 to 5 real examples]. Must NOT match: [3 to 5 near misses]. Explain each part of the pattern, then walk through every example above and say whether it matches.
Positive and negative examples turn "match a UK postcode" from a guess into a specification. Still run the pattern against your own samples in a real test before you ship it.
Safety rules for coding with AI
- Never paste secrets. API keys, passwords, tokens, connection strings, private keys and customer data stay out of prompts. Swap them for placeholders like
API_KEY_HEREfirst. If one slips through, rotate it. - Follow your company's policy. Many teams restrict which assistants can see proprietary code. Check before you paste.
- Verify every package and API. Models sometimes suggest functions that don't exist, or that were renamed in a later version. Check the official docs and the package registry before installing anything a model recommends.
- Run the tests. Treat AI output like a pull request from a fast, confident junior developer: read it, run it, test it. If there are no tests, write them first.
- Review security-sensitive code by hand. Authentication, payments, file uploads, SQL built from user input and anything involving
evaldeserve human eyes every time. - Ask where the model is unsure. Adding "tell me which parts of your answer you're least confident about" surfaces weak spots you'd otherwise miss.
Most bad AI code traces back to the same root causes as weak prompts in general, which our guide to common prompt mistakes covers in more detail.
Keep your best coding prompts reusable
Once a template works, save it. A single notes file with your debugging, review and test prompts saves you from retyping the same context every day. Keep a short "stack block" (languages, versions, conventions) that you paste at the top of every coding prompt, or put it in your assistant's custom instructions so it's always there.
If you'd rather not maintain templates by hand, a prompt generator such as Promptay turns a one-line idea like "review this Django view for security issues" into a structured prompt with role, task, context, format and constraints, ready to open in ChatGPT, Claude or Gemini.
Frequently asked questions
What is the best ChatGPT prompt for debugging code?
The best debugging prompt reads like a good bug report: your language and versions, the full error and stack trace, expected versus actual behavior, what you already tried, and a minimal snippet that reproduces the problem. Ask the model to rank its hypotheses before proposing a fix, and to ask you for missing information instead of guessing.
Is it safe to paste my code into ChatGPT?
It depends on the code and on your company's policy. Never paste secrets, credentials or customer data; replace them with placeholders first. For proprietary code, check which AI tools your team is allowed to use and whether your account's data settings meet your organization's requirements.
Can ChatGPT review code as well as a human?
It's good at quickly catching common bugs, missing edge cases and obvious security issues, especially when you scope the review tightly. It doesn't know your business rules, your team's history or why a strange piece of code exists, so treat its review as a fast first pass that a human still approves.
How do I stop ChatGPT from inventing functions or libraries?
Give it your exact versions, paste the relevant types or schema, and tell it to say when it isn't sure rather than guess. Then confirm any unfamiliar function in the official documentation, and check that a recommended package really exists in its registry before you install it.
Do these coding prompts work in Claude and Gemini too?
Yes. The structure of context, task, constraints and output format works in any current assistant, including Claude, Gemini and Copilot Chat. There are small differences in how each handles long files and formatting, which our ChatGPT vs Claude vs Gemini guide covers.
Keep reading
· 10 min read
AI prompts for business plans: market research, financials and pitch decks
ChatGPT prompts for business plan writing, section by section: market sizing, competitors, financials and pitch decks, with checks that keep numbers honest.
Read article· 9 min read
AI prompts for studying: study plans, flashcards and practice tests
ChatGPT prompts for studying built on active recall and spaced repetition: templates for study plans, flashcards, practice tests and honest essay feedback.
Read article· 9 min read
ChatGPT vs Claude vs Gemini: how to adapt your prompts to each
ChatGPT vs Claude vs Gemini prompts: what works in all three, how each handles structure, length and long documents, and one portable template to copy.
Read article
Prompt templates for this topic
Code review prompt template
An AI code review prompt that finds real bugs and edge cases instead of style nitpicks: ranked issues, corrected snippets and one-line explanations.
View templateSQL query prompt template
An AI prompt for writing correct SQL from a plain-language question: give the schema, the dialect and the edge cases, and get a query with an explanation you can check.
View template