PortuguêsEspañol

AI Prompts for Coding in 2027: 16 Tested Prompts for Legacy Code, Tests, Debugging and SQL

OBy Onne Company · Published
Quick answer: Good AI prompts for coding name the stack and version, include the real code or error, define the answer format and say what the AI must not do. Below are 16 tested prompts for legacy code, tests, debugging, PRs, SQL and client messages, four of them with real outputs. They work in ChatGPT, Claude, Gemini and Copilot Chat.
AI Prompts for Coding in 2027: 16 Tested Prompts for Legacy Code, Tests, Debugging and SQL
In this article
  1. Why these prompts work
  2. Understanding code that isn't yours
  3. Tests
  4. Debugging
  5. Review and PRs
  6. Database
  7. Documentation
  8. Clients, PMs and the people around the code
  9. Common mistakes with coding prompts
  10. Want to skip this part?
  11. Frequently asked questions
  12. Sources

These are 16 AI prompts for coding that hold up in the daily work of a product team and a freelance gig: understanding legacy code, writing tests, debugging, reviewing your own PR, speeding up SQL and talking to the people who pay for the code. Each one has when to use it, the text to copy and, in four of them, the actual output the AI returned. They work in ChatGPT, Claude, Gemini and Copilot Chat.

One rule before you copy anything: no secrets, tokens, .env files or real customer data in the prompt. Swap them for fake values.

Why these prompts work

A coding prompt that works has four parts: the stack and version (PHP 7.4 and PHP 8.3 are practically different languages), the real code or the real error, the shape of the answer you want, and what the AI must not do (invent libraries, change behavior, touch files you didn't mention). That last part is the one people skip. Without it, you ask for an explanation and get the function rewritten.

Understanding code that isn't yours

1. Explain legacy code, separating fact from guess

When to use it: a ticket lands in an old file with no tests and nobody who remembers why it works this way.

Explain the function below to a developer who will change it tomorrow. Language: [LANGUAGE AND VERSION].
Answer in 4 parts:
1. What it calculates, in 3 sentences
2. Inputs and output, with the likely type of each
3. Odd or dangerous behavior (type coercion, rule order, magic numbers)
4. Questions I need answered before changing it
Tag with [FACT] what is in the code and with [GUESS] what you inferred from names. Do not rewrite the function.

[CODE]

Real output, for a shipping function in PHP 7.4:

function calcShipping($w, $zip, $t) {
  $s = 0;
  if (substr($zip, 0, 1) < 4) $s = 9; else $s = 14;
  if ($w > 30) $s = $s + ($w - 30) * 0.5;
  if ($t == 2) $s = $s * 1.6;
  if ($s > 60) $s = 60;
  return round($s, 2);
}

1. What it calculates. A shipping price from weight, ZIP code and shipping type. There's a base rate by region, a surcharge per unit of weight over 30, a multiplier for type 2 and a cap of 60. [FACT]

2. Inputs and output. $w: weight, probably in pounds (the 30 cutoff suggests it) [GUESS]. $zip: a string; only the first digit matters [FACT]. $t: shipping type, and 2 looks like expedited [GUESS]. Output: float rounded to 2 decimals [FACT].

3. Dangerous spots. (a) ZIPs starting with 0 to 3 (roughly the East Coast and parts of the Southeast) pay 9; everything else pays 14 [FACT in code, GUESS about intent]. (b) Empty ZIP: substr('', 0, 1) returns false on PHP 7.4, and false compared to 4 is true, so an empty ZIP gets the cheapest rate [FACT]. (c) The cap applies after the multiplier, so heavy expedited costs the same as heavy standard [FACT]. (d) 0.5, 30, 1.6 and 60 are bare numbers with no constant [FACT].

4. Questions before changing it. Should the 60 cap apply to expedited too? Do ZIPs arrive validated, or can ZIP+4 and blanks get through? Are there values of $t other than 1 and 2? Who else calls this function (cart, admin panel, partner API)?

Item (b) is the kind of bug nobody goes looking for. That alone was worth the prompt.

2. Impact map before a change

When to use it: you're about to change a function and want to know what else moves. Works best in an agent that can search the repo.

I'm going to change [FUNCTION/CLASS] in [FILE] to [CHANGE]. Search the repository and list:
1. Every place that calls it, with file and line
2. Which tests cover those places, and which have no test
3. Data or contracts that could break (API responses, DB columns, queue messages)
4. The order in which I should make the change to keep main deployable
Don't edit any file. Only report.

Tests

3. Edge cases before the test

When to use it: before writing tests for a function with business rules.

Here's a [LANGUAGE] function. Before writing any test, list 10 inputs that could break it, ordered by how likely they are to happen in production. For each: the input, the expected behavior and why it's risky. Then write one test per case in [TEST FRAMEWORK], following the style of this existing test: [EXAMPLE TEST].

[CODE]

Real output, for a function that prorates a monthly subscription when the customer upgrades mid-cycle (amounts in cents):

1. Upgrade on the first day of the cycle: should charge the full difference, not zero. Off-by-one in day counting is the most common bug here.

2. Upgrade on the last day: should charge one day's difference, not a negative or zero amount.

3. Cycle that spans February: 28 or 29 days. If the code assumes 30, the daily rate is wrong for every February customer.

4. Cycle that starts on the 31st: the next renewal date in a 30-day month must not skip into the following month.

5. Daylight saving change inside the cycle: if you count hours and divide by 24, one day becomes 23 or 25 hours and the result shifts.

6. Rounding: $29.99 to $49.99 over 31 days produces fractional cents. Decide rounding once and test that the sum of daily charges matches the total.

7. Downgrade: should produce a credit, not a negative charge sent to the payment provider.

8. Two upgrades on the same day: the second must prorate from the new plan, not the original.

9. Upgrade at 11:30 p.m. in the customer's time zone, already "tomorrow" in UTC: which day counts?

10. Free plan to paid: the old price is zero; make sure there's no division by the old amount anywhere.

Items 5 and 9 are the ones a human forgets at the end of the day. Both are real support tickets waiting to happen.

4. Characterization test

When to use it: you'll refactor legacy code and need to freeze current behavior, bugs included.

Write characterization tests in [FRAMEWORK] for the code below. The goal is to lock in CURRENT behavior, even if it looks wrong. For each test, add a comment saying whether the behavior looks intentional or looks like a bug. Don't fix anything in the code.

[CODE]
Advertisement

Debugging

5. Stack trace into hypotheses

When to use it: an error in production and you don't know where to start.

Stack: [LANGUAGE, FRAMEWORK, VERSION]. Error in production: [STACK TRACE]. Context: [WHAT CHANGED RECENTLY, HOW OFTEN IT HAPPENS].
Give me up to 5 hypotheses ordered by likelihood. For each: why it fits the trace, how to confirm it in under 15 minutes (log, query, test), and what the fix would be. Do not suggest wrapping things in try/catch to hide the error.

Real output, for an intermittent TypeError: Cannot read properties of undefined (reading 'id') in a Node webhook handler for payment events, happening "a few times a day" after a deploy:

1. Events arriving out of order (most likely). The handler probably looks up the order created by an earlier event. If payment.succeeded arrives before your code finished saving the order from checkout.completed, the lookup returns undefined. Confirm: log the event type and timestamp next to the failing order id and check whether the order existed at that moment. Fix: if the order isn't there yet, return a non-2xx status so the provider retries, or queue the event.

2. A new event type hitting the same handler. If the deploy subscribed to more events, one of them may not carry the object you expect. Confirm: group failures by event type. Fix: switch on type and ignore what you don't handle.

3. Test-mode events reaching production. Confirm: check the livemode flag on failing payloads. Fix: reject mismatched mode.

4. Duplicate delivery. The second delivery runs after the first deleted or moved the record. Confirm: look for repeated event ids. Fix: store processed event ids and skip repeats.

6. The bug that only happens sometimes

When to use it: flaky behavior you can't reproduce on demand.

This bug happens about [FREQUENCY] and I can't reproduce it locally: [DESCRIPTION]. Relevant code: [CODE]. List what typically makes behavior intermittent in this kind of code (concurrency, cache, time, ordering, retries, environment differences) and, for each, the logging I should add to catch it next time. Keep the logging free of personal data.

Review and PRs

7. Review your own diff before opening the PR

When to use it: always, especially on a solo project with no reviewer.

Review this diff as a strict senior reviewer would. Look only for: security issues (OWASP Top 10), likely bugs, missing tests for changed behavior and performance problems. Ignore style. List at most 6 points, most severe first, each with file, line and a concrete fix. If you find nothing serious, say so.

[DIFF]

8. A PR description reviewers actually read

When to use it: a PR with more than a handful of files.

Write a PR description from this diff and ticket. Sections: What changed (3 bullets max), Why, How to test (exact steps), Risks and rollback, Screenshots needed (yes/no). Plain language, no filler. Ticket: [TICKET]. Diff: [DIFF]

Database

9. Slow query with EXPLAIN

When to use it: an endpoint or report got slow.

Postgres [VERSION]. This query is slow: [QUERY]. Schema and indexes: [CREATE TABLE AND INDEXES]. EXPLAIN ANALYZE output: [OUTPUT].
Explain where the time is going in plain words, propose a rewrite and/or an index, and tell me how to check the improvement. Point out anything in the query that changes results, not only speed.

Real output, for a daily sales report filtering with WHERE DATE(created_at) = '2026-10-15' on a timestamptz column with an index on created_at, about 4 million rows:

Where the time goes: the plan shows a sequential scan over the whole table. DATE(created_at) wraps the column in a function, so Postgres can't use the index on created_at.

Rewrite: filter on a range instead: WHERE created_at >= '2026-10-15 00:00:00-04' AND created_at < '2026-10-16 00:00:00-04'. That uses the existing index, no new index needed.

Results, not just speed: DATE() on a timestamptz uses the session time zone, which on most servers is UTC. That means your "October 15" report currently runs from 8 p.m. Eastern on the 14th to 8 p.m. on the 15th. Evening orders land on the wrong day. The range above uses Eastern time (UTC-4 in October); store the business time zone in config instead of hard-coding the offset, since it changes to UTC-5 in November.

How to check: rerun EXPLAIN ANALYZE and look for an Index Scan or Bitmap Index Scan on created_at, and compare the row count against the old query for one day to measure how many orders were shifting.

The speed fix was expected. The time zone finding is the one that changes the numbers your finance team has been reading.

10. Migration that doesn't take production down

When to use it: adding a column, an index or a constraint on a big table.

I need to [CHANGE] on table [TABLE] with about [N] rows in [DATABASE AND VERSION], with no downtime. Write the migration in steps (expand, backfill, contract), say which steps lock the table and for how long, and how to roll back each one. Use [MIGRATION TOOL] syntax.

Documentation

11. Onboarding README

From the repo structure and these files [PACKAGE FILE, DOCKER-COMPOSE, .env.example], write a README for a new developer: how to run it locally in under 15 minutes, how to run tests, where the main parts of the code live, and the 3 most common setup errors with their fix. Don't invent commands that aren't in the files.

12. Architecture decision record (ADR)

Write an ADR for this decision: [DECISION]. Context: [CONTEXT]. Options considered: [OPTIONS]. Format: Title, Status, Context, Decision, Consequences (good and bad), Options rejected and why. Keep it under one page. Flag anything I said that sounds like a guess rather than a measured fact.

Clients, PMs and the people around the code

13. Contract quote that doesn't forget half the work

A client wants: [REQUEST]. Break it into deliverables and list everything they didn't mention but will expect (auth, password reset, emails, admin, privacy policy and US state privacy requirements if they collect personal data, payments, sales tax, hosting, backups). For each item, a rough range in hours. I'll set the final number myself.

14. Telling the PM about a slip without sounding like an excuse

Write a short Slack message to my PM. Facts: [WHAT SLIPPED, WHY, NEW DATE, WHAT I NEED FROM THEM]. Tone: direct, no apologizing three times, no blaming anyone. Offer one option to cut scope and keep the original date.

15. On-call handoff note

Turn these notes from my on-call week into a handoff for the next person: [NOTES]. Sections: open incidents, alerts that fired and were noise, things that are fragile right now, what I would watch first. Keep it scannable.

16. A junior learning from work code

I'm a junior developer. Explain this code from my job as a tutor would: [CODE]. Don't rewrite it. Ask me 3 questions to check if I understood, wait for my answers, and only then tell me what I got wrong.
Advertisement

Common mistakes with coding prompts

  • Leaving out the version. React 17 and React 19, Python 3.8 and 3.12: answers change a lot.
  • Asking for the fix before the diagnosis. You get a patch that hides the symptom.
  • Pasting secrets "just this once." Rotate the key the moment you notice.
  • Not saying what it can't do. "Don't change behavior" and "don't add libraries" save hours.
  • Trusting the package name. Check every new dependency on the official registry before installing.

Prompts get you the first draft of the work. If you want the work to happen without asking every time, like a reviewer that comments on every PR the moment it opens, see AI for developers. For which tool to run these in and what each one costs, read the AI for coding guide.

Ready-made AI agents for developers

Want to skip this part?

Ready-made AI agents for developers and software teams: nothing to build, no prompts, already working for you.

  • First-pass review on every pull request, with your team's rules, in GitHub
  • Support tickets turned into clean issues with repro steps and suggested priority
  • Security checks for secrets, injection and access control before a human reviews
I want the ready-made agents

Frequently asked questions

What makes a good AI prompt for coding?

Stack and version, the real code or error, the format you want back, and what the AI must not do, such as invent libraries or change behavior. The last part is the one most people skip.

Which AI is best for these coding prompts?

They work in ChatGPT, Claude, Gemini and Copilot Chat. For long files and multi-step answers I'd use Claude; for prompts that need to search the repo, use an agent like Claude Code or Codex.

Can I paste my company's code into these prompts?

Only if your company's AI policy allows it, preferably on a business plan that doesn't train on your data. Never paste secrets or real customer data.

Do AI prompts work for debugging?

Yes, if you ask for ranked hypotheses with a way to confirm each, not for a direct fix. Asking for the fix first usually gets you a patch that hides the symptom.

Sources

O

Onne Company · the Núcleo Aprendizado team

We test, compare and explain what is worth learning, with a focus on what gets results at work. How we work.

Read next