Blog

What AI Thinks About Business Logic in SQL Stored Procedures

What AI Thinks About Business Logic in SQL Stored Procedures

My short answer: put the logic that shapes data in the database, and keep application code for what truly lives outside it.

This has been one of the hottest debates in software for decades. One camp treats stored procedures as the natural home for all data transformation logic, and the other bans them outright. Developer forums are full of complaints from people whose code reviews were rejected, or whose work was criticized, simply for putting logic into sprocs.

AI-assisted development has changed the tone of that argument. Instead of joining a camp, an AI assistant weighs each case on its reasons. It is striking how often AI now suggests a stored procedure itself, and explains why: set-based work, atomic changes, a clean security boundary. The rest of this post is that case-by-case reasoning.

Where stored procedures earn their place

I write and review a lot of both SQL and application code, and I don't share the dogma on either side. Stored procedures are the right tool when the logic is really a statement about data, not about its representation or visualization.

  • Set-based work. Moving a million rows with one MERGE beats pulling them over the wire, looping in C# or Python, and pushing them back.
  • No network round trips. Business logic in application code has to pull every row it needs out of the database, then send every result back to be saved. That doubles the traffic, adds latency to each step and multiplies with every call. A procedure reads, computes and writes in one place, and only the final answer crosses the network. The hidden cost is on the server. Thousands of small calls mean thousands of concurrent connections, and each active request holds a worker thread. Worker limits are tied to the number of cores, so the threads run out while the CPU still looks underused. The only fix is buying more vCores just to hold connections, and the database bill ends up higher than if the logic had lived inside it.
  • Atomic multi-table changes. A transaction that must succeed or fail as a unit is safest where the data lives.
  • Debugging. You can run a procedure against real data, step through it, and inspect every intermediate result with a plain SELECT. Reproducing a bug means re-running it with the same parameters. Chasing the same rule through an app's controllers, services, ORM and logs is a far harder job.
  • Version control and deployment. Microsoft's SQL Server database projects solved this years ago. Procedures live in Git like any other code, and a GitHub Actions pipeline compares the project with the target database and applies only what changed. A procedure deploy is often smaller and less stressful than an app release.
  • Data integrity. Constraints, triggers and procedures that enforce invariants protect the data from every client, including the ones nobody remembers writing.
  • Permissions. Granting EXECUTE on a procedure while denying direct table access is a clean, auditable security boundary.
  • Batch and ETL jobs. Loading, deduplicating and reconciling files close to the data is fast and simple.

Where they hurt

Stored procedures are not free of trade-offs. These are the real ones.

  • Scaling is lopsided. You can add application servers cheaply, while database CPU is the most expensive kind to add. CPU-heavy math that does not need to sit next to the data is better off in code.
  • Portability disappears. Dialect-specific procedural code ties the business to one vendor, and a migration becomes a rewrite.
  • Knowledge gets siloed. Fewer developers read procedural SQL fluently, so the rules end up understood by one or two people. Years of "keep logic out of the database" advice have made true SQL specialists genuinely rare. Companies that have them should treat them as key people and work hard to keep them.

What AI-assisted development changes

AI coding tools have removed most of the old objections to database code.

An AI assistant refactors procedures, traces dependencies across a schema and reviews SQL as readily as application code. Buying a specialized SQL code analyzer makes little sense when your AI coding assistant already does that work.

AI is also very good at writing and tuning set-based SQL, so the data-heavy work that belongs in the database is cheaper to get right than it used to be.

One caution remains. Give the assistant the real schema, triggers, permissions and data volumes, because a procedure read in isolation can look right and still fail in production.

A real example: logic in the database, cost kept low

Keeping logic in the database doesn't mean hitting the database on every page view. The Crypto Jobs page on stas.club shows how to have both.

The job postings live in an Azure SQL database, and the procedures there decide which postings are crypto-related and shape the list. That is data logic, so it stays in the database. But a public page that anyone can load at any time would keep the database awake, and a serverless Azure SQL database that has to wake up costs money and can stall the page for minutes.

So the page never touches the database:

  1. A daily scheduled job on Google Cloud calls the site's web API. The job holds no business logic; the API and the procedures behind it do the work, so the same refresh can also be run by hand.
  2. The API runs the procedures and returns the finished list.
  3. The job writes that list as a JSON file to a Cloudflare R2 bucket on the free tier.
  4. When someone opens the page, the site reads the prepared file from R2. The database isn't involved at all.

The result is one database call a day instead of one per visitor. The rules still live in one place, the page loads instantly, and the database can sleep the rest of the day.

A rule of thumb for deciding

Ask what the logic is about. If it describes how data must be shaped, moved or protected, it belongs in the database. If it needs things outside the database, such as live external data, network calls or the user interface, it belongs in code.

LogicBetter homeWhy
Bulk load, merge, deduplicateStored procedureSet-based and next to the data
Referential and uniqueness rulesConstraintsEnforced for every client
Row-level access controlDatabase permissionsOne enforcement point
Pricing, discounts, scoringStored procedureSet-based, one answer for every consumer, easy to inspect
Workflow and approval statesStored procedureAllowed transitions enforced and auditable in one place
Rules that need live data (market prices, API feeds)Application codeThe data lives outside the database
Calls to external servicesApplication codeThe database should not make network calls

The verdict

Stored procedures are a good home for business logic, not a poor one. Rules that are about the data, such as scoring, pricing, workflow states and integrity, belong next to it. There they run set-based, give every consumer the same answer and are easy to inspect. Keep application code for what truly lives outside the database: live external data, network calls and the user interface.

Some engineers will still disagree, and a few have real reasons: a team with little SQL skill, or a database already at its compute limit. For everyone else, ask what a rule is about and put it where that data lives. Make that choice on purpose, not by habit.

← All posts