{"id":25,"date":"2024-08-24T11:25:58","date_gmt":"2024-08-24T10:25:58","guid":{"rendered":"https:\/\/contentlabstudy.com\/soft\/?p=25"},"modified":"2026-09-24T21:15:30","modified_gmt":"2026-09-24T20:15:30","slug":"sql-for-business-logic","status":"publish","type":"post","link":"https:\/\/contentlabstudy.com\/soft\/sql-for-business-logic\/","title":{"rendered":"SQL for Business Logic"},"content":{"rendered":"<p>Put <strong>business rules next to the data they protect<\/strong> when the rule is set-based, must hold for every writer, and would be a race if you only enforced it in app code. That is what SQL is for: constraints, transactions, and queries over sets. It is not where HTML belongs, and it is not where you call a payment HTTP API.<\/p>\n<h2>What belongs in the database<\/h2>\n<ul>\n<li><strong>Invariants the data must never violate:<\/strong> foreign keys, unique (email, tenant), check constraints, <code>NOT NULL<\/code>.<\/li>\n<li><strong>Atomic multi-row changes:<\/strong> transfer money, allocate inventory. One transaction, one commit.<\/li>\n<li><strong>Set operations:<\/strong> \u201call overdue invoices for these 50k accounts\u201d \u2014 do not load rows into memory to filter.<\/li>\n<\/ul>\n<h2>What does not<\/h2>\n<ul>\n<li>Orchestration (send email, call Stripe, publish events) \u2014 that is application code, maybe outbox-in-the-same-transaction.<\/li>\n<li>Presentation formatting and localization.<\/li>\n<li>Rules that change weekly and need a deploy of stored procedures nobody can test.<\/li>\n<\/ul>\n<h2>Example: inventory without a lost update<\/h2>\n<pre><code>BEGIN;\nUPDATE sku\n   SET qty = qty - 1\n WHERE id = $1 AND qty &gt;= 1;\n-- 0 rows: sold out. Do not \u201cread then write\u201d without locking.\nCOMMIT;\n<\/code><\/pre>\n<p>A read in the API, a think, then an update is how you oversell. Constraints plus a single statement (or <code>SELECT \u2026 FOR UPDATE<\/code>) close the race. Check that the update changed one row. The unique key is the same idea for a fact that must not be stored twice:<\/p>\n<pre><code>ALTER TABLE customer\n  ADD CONSTRAINT uq_customer_email UNIQUE (tenant_id, email);<\/code><\/pre>\n<h2>Transactions and isolation<\/h2>\n<p>PostgreSQL and SQL Server default to <code>READ COMMITTED<\/code>; MySQL InnoDB defaults to <code>REPEATABLE READ<\/code>. Either default is fine until it is not. Raising the isolation level does not fix the lost update in the example above. Phantom reads and write skew need a documented isolation level or an explicit lock. Keep transactions short: no HTTP inside a transaction. For \u201csave entity then publish event,\u201d use an <strong>outbox table<\/strong> in the same commit, not a second connection after commit.<\/p>\n<h2>What breaks it<\/h2>\n<p>Two callers can both read the same <code>qty<\/code> and both write <code>qty - 1<\/code>. Use the single <code>UPDATE<\/code> above, and treat a row count of 0 as sold out.<\/p>\n<pre><code>static async Task LostUpdate(DbConnection conn, int id, CancellationToken ct)\n{\n    int qty;\n    await using (var read = conn.CreateCommand())\n    {\n        read.CommandText = \"SELECT qty FROM sku WHERE id = $1\";\n        var idParam = read.CreateParameter();\n        idParam.Value = id;\n        read.Parameters.Add(idParam);\n        qty = (int)(await read.ExecuteScalarAsync(ct))!;\n    }\n\n    if (qty &lt; 1)\n        return;\n\n    await using var write = conn.CreateCommand();\n    write.CommandText = \"UPDATE sku SET qty = qty - 1 WHERE id = $1\";\n    var writeParam = write.CreateParameter();\n    writeParam.Value = id;\n    write.Parameters.Add(writeParam);\n    await write.ExecuteNonQueryAsync(ct);\n}<\/code><\/pre>\n<h2>Pitfalls<\/h2>\n<ul>\n<li>Business logic only in the ORM, none in constraints \u2014 a one-off SQL script will corrupt data.<\/li>\n<li>Triggers that hide writes (you cannot see the story in the app).<\/li>\n<li>Stored procedures as the entire application: undebuggable, unversioned, duplicated per environment.<\/li>\n<\/ul>\n<p>See <a href=\"\/soft\/database-normalization\/\">normalization<\/a> and <a href=\"\/soft\/orm-features\/\">ORM features<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Put business rules next to the data they protect when the rule is set-based, must hold for every writer, and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[3],"tags":[],"class_list":["post-25","post","type-post","status-publish","format-standard","hentry","category-software-development"],"_links":{"self":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/25","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/comments?post=25"}],"version-history":[{"count":4,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/25\/revisions"}],"predecessor-version":[{"id":3225,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/posts\/25\/revisions\/3225"}],"wp:attachment":[{"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/media?parent=25"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/categories?post=25"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/contentlabstudy.com\/soft\/wp-json\/wp\/v2\/tags?post=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}