/

/

Where Should Business Logic Live: SQL vs Application Code?

Content

Where Should Business Logic Live: SQL vs Application Code?

Where Should Business Logic Live: SQL vs Application Code?

Where Should Business Logic Live: SQL vs Application Code?

The Debate That Never Ends

Should price calculations happen in a stored procedure or in your API layer? Should data validation fire in a database trigger or in your application code?

The Case for Business Logic in SQL

Data Integrity Is Guaranteed

When logic lives in the database, it enforces rules regardless of which application writes data.

Performance for Set-Based Operations

SQL is purpose-built for operating on sets of rows. Aggregation queries are faster than fetching rows and summing in a loop.

Example: Price Calculation in SQL

CREATE PROCEDURE calculate_order_total(
  IN p_order_id INT,
  IN p_user_tier VARCHAR(20)
)
BEGIN
  DECLARE base_total DECIMAL(10,2);
  DECLARE discount_rate DECIMAL(4,2);
  SELECT SUM(quantity * unit_price) INTO base_total
  FROM order_items WHERE order_id = p_order_id;
  SET discount_rate = CASE p_user_tier
    WHEN 'gold' THEN 0.15 WHEN 'silver' THEN 0.08 ELSE 0.00 END;
  UPDATE orders SET total_amount = base_total * (1 - discount_rate)
  WHERE order_id = p_order_id;
END;

The Case for Application Code

Testability and Maintainability

Unit testing a Python function is straightforward. Testing a stored procedure requires a running database.

Example: Price Calculation in TypeScript

const DISCOUNT_RATES = { gold: 0.15, silver: 0.08, bronze: 0.03 };
async function calculateOrderTotal(orderId, userTier) {
  const items = await db.query('SELECT quantity, unit_price FROM order_items WHERE order_id = $1', [orderId]);
  const baseTotal = items.rows.reduce((sum, row) => sum + row.quantity * row.unit_price, 0);
  const finalTotal = baseTotal * (1 - (DISCOUNT_RATES[userTier] ?? 0));
  await db.query('UPDATE orders SET total_amount = $1 WHERE order_id = $2', [finalTotal, orderId]);
  return finalTotal;
}

When to Use What

SQL-Side Logic For:

  • Reporting and analytics queries

  • Data integrity constraints

  • Audit logging via triggers

  • Bulk data transformations

Application Code For:

  • Complex workflows with external calls

  • Rules that change frequently

  • Cross-service logic

  • Anything that needs unit tests

Rapid Prototyping with AI2SQL

AI2SQL makes prototyping business logic as SQL fast. Describe your rule in plain English and get working SQL to verify it produces the right results before deciding where it belongs.

Decision Framework

  1. Does it need to be enforced regardless of caller? Database constraint

  2. Is it a read-only aggregation? SQL query or view

  3. Does it involve external systems? Application code

  4. Will it change frequently? Application code

  5. Is it a bulk transformation? SQL

Share this

More Articles

More Articles

More Articles