Database Programming Features · Lesson 80 of 112

Database Stored Procedures and Functions

What you will learn

  • What a stored procedure and a stored function are
  • The difference between a procedure that is called and a function used inside a query
  • The advantages and costs of keeping logic in the database
  • What SQLite offers instead, with a runnable example
  • How to decide where a rule should live

1. Logic inside the database

Until now, every rule you ran lived in your Python program, and the database only stored data. Many database systems let you save named pieces of code inside the database itself. There are two kinds:

Kind How it is used What it is for
Stored procedure you call it by name (CALL transfer(...)) do a job: several statements that change data
Stored function you use it inside a query (SELECT my_function(price) ...) compute and return a value

A stored procedure is like a recipe card kept in the kitchen: any cook, in any language, can say "make the transfer recipe" and get the same steps carried out.

In PostgreSQL, for example, the official documentation says that CREATE PROCEDURE defines a new procedure and that you use CALL to execute it. Its own example is:

CREATE PROCEDURE insert_data(a integer, b integer)
LANGUAGE SQL
AS $$
INSERT INTO tbl VALUES (a);
INSERT INTO tbl VALUES (b);
$$;

CALL insert_data(1, 2);

(This is PostgreSQL syntax, shown from its documentation page for CREATE PROCEDURE. It is not run here, because SQLite has no stored procedures.) The PostgreSQL documentation describes CREATE FUNCTION in the same way: it defines a new function. Other systems have their own syntax and their own procedure languages, so always read the documentation of the product you use.

2. Why teams use them

  • One copy of the rule. If five programs (a website, a mobile app, a report script...) all need "transfer money", the rule can live once in the database instead of five times in five languages.
  • Fewer round trips. The program sends one call; the steps run next to the data, so many statements do not each travel across the network (lesson 1.5).
  • Control. You can let a user run a procedure without letting them touch the tables directly (lesson 8.4).

3. Why teams avoid them

  • Hard to test and version. Application code sits in files, with tests and version control. Database routines are easy to forget in both.
  • Hidden logic. Like triggers (lesson 11.1), a routine can surprise a developer who only reads the application.
  • Tied to one product. A procedure written for one system usually must be rewritten for another.
  • Harder to scale. The database is often the one machine that is hardest to make bigger (chapter 14), so putting heavy work there can slow everyone.

Neither side is "right". It is a design choice, and many successful systems use only application code, while others use routines heavily.

4. What SQLite offers instead

SQLite has no stored procedures. It is a library inside your program (lesson 1.5), so the "database side" and the "application side" already run in the same process. There are two nearby tools.

A routine in your application. Wrap the steps in one function and one transaction (lesson 6.2). Every program that uses it shares the same rule:

import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER CHECK (balance >= 0));
INSERT INTO accounts (owner, balance) VALUES ('Rina', 500), ('Sam', 100);
""")

def transfer(con, src, dst, amount):
    """A routine kept in the application: the nearest thing SQLite has to a stored procedure."""
    with con:
        con.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src))
        con.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst))

transfer(con, 1, 2, 200)
print(con.execute("SELECT owner, balance FROM accounts").fetchall())
try:
    transfer(con, 2, 1, 1000)
except sqlite3.IntegrityError as e:
    print("refused:", e)
print(con.execute("SELECT owner, balance FROM accounts").fetchall())
[('Rina', 300), ('Sam', 300)]
refused: CHECK constraint failed: balance >= 0
[('Rina', 300), ('Sam', 300)]

The second transfer would leave Sam below zero, so the CHECK rule refused it and the with con: block rolled back the first UPDATE too. Nothing changed.

A function registered with the database. Python can teach SQLite a new function that can be used inside SQL, like a stored function:

def taka(amount):
    return f"Tk {amount:,}"

con.create_function("taka", 1, taka, deterministic=True)
print(con.execute("SELECT owner, taka(balance * 1000) FROM accounts").fetchall())
[('Rina', 'Tk 300,000'), ('Sam', 'Tk 300,000')]

create_function("taka", 1, taka) registers a function named taka that takes one argument. deterministic=True promises that the same input always gives the same output. The function lives only for this connection: it is not saved in the database file, so each program must register it again. That is a real difference from a stored function, which is saved inside the database.

And a procedure call is simply not understood:

try:
    con.execute("CALL transfer(1, 2, 10)")
except sqlite3.OperationalError as e:
    print("error:", e)
error: near "CALL": syntax error

The same routine as SQL cells, on the sample data. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Reset data starts again. SQL has no function to call here, so the cells write the steps of the routine out as one transaction. Moving one unit from row 1 to row 2 (the CHECK rule on the column keeps the value from going negative):

Move one unit of stock from product 2 to product 1 (products.stock has CHECK (stock >= 0)):

SELECT product_id, stock FROM products WHERE product_id IN (1, 2) ORDER BY product_id;
BEGIN;
UPDATE products SET stock = stock - 1 WHERE product_id = 2;
UPDATE products SET stock = stock + 1 WHERE product_id = 1;
COMMIT;
SELECT product_id, stock FROM products WHERE product_id IN (1, 2) ORDER BY product_id;
product_id  stock
----------  -----
         1      0
         2    150
(2 rows)

product_id  stock
----------  -----
         1      1
         2    149
(2 rows)

Now try to move far more than product 1 has. The rule refuses it, and the rollback ends the transaction:

BEGIN;
(done)
UPDATE products SET stock = stock - 1000000 WHERE product_id = 1;
IntegrityError: CHECK constraint failed: stock >= 0
ROLLBACK;
SELECT product_id, stock FROM products WHERE product_id IN (1, 2) ORDER BY product_id;
product_id  stock
----------  -----
         1      1
         2    149
(2 rows)

Move 1.00 (100 cents) from account 1 to account 2 (accounts.balance_cents has CHECK (balance_cents >= 0)):

SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 100 WHERE account_id = 1;
UPDATE accounts SET balance_cents = balance_cents + 100 WHERE account_id = 2;
COMMIT;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id  balance_cents
----------  -------------
         1         192400
         2          52078
(2 rows)

account_id  balance_cents
----------  -------------
         1         192300
         2          52178
(2 rows)

Now try to move far more than account 2 has. The rule refuses it, and the rollback ends the transaction:

BEGIN;
(done)
UPDATE accounts SET balance_cents = balance_cents - 100000000 WHERE account_id = 2;
IntegrityError: CHECK constraint failed: balance_cents >= 0
ROLLBACK;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id  balance_cents
----------  -------------
         1         192300
         2          52178
(2 rows)

Move one seat of capacity from section 1 to section 2 (sections.capacity has CHECK (capacity > 0)):

SELECT section_id, capacity FROM sections WHERE section_id IN (1, 2) ORDER BY section_id;
BEGIN;
UPDATE sections SET capacity = capacity - 1 WHERE section_id = 1;
UPDATE sections SET capacity = capacity + 1 WHERE section_id = 2;
COMMIT;
SELECT section_id, capacity FROM sections WHERE section_id IN (1, 2) ORDER BY section_id;
section_id  capacity
----------  --------
         1        25
         2        30
(2 rows)

section_id  capacity
----------  --------
         1        24
         2        31
(2 rows)

Now try to remove far more than section 2 has. The rule refuses it, and the rollback ends the transaction:

BEGIN;
(done)
UPDATE sections SET capacity = capacity - 1000000 WHERE section_id = 2;
IntegrityError: CHECK constraint failed: capacity > 0
ROLLBACK;
SELECT section_id, capacity FROM sections WHERE section_id IN (1, 2) ORDER BY section_id;
section_id  capacity
----------  --------
         1        24
         2        31
(2 rows)

And a procedure call is simply not understood by SQLite:

CALL transfer(1, 2, 10);
OperationalError: near "CALL": syntax error
CALL transfer(1, 2, 10);
OperationalError: near "CALL": syntax error
CALL transfer(1, 2, 10);
OperationalError: near "CALL": syntax error
Quick check: why is a Python function registered with create_function not a stored function?

A stored function is saved in the database, so every program sees it. A registered function exists only in the one connection that registered it, and disappears when that connection closes.

Worked example: where should the rule live?

A shop must never sell more units than are in stock. Three places could enforce it:

Place How Good for Weak spot
A CHECK (stock >= 0) constraint database refuses the update a simple rule that must always hold cannot do complex logic
A trigger or stored procedure database runs code rules every program must obey hidden, product-specific
Application code the program checks first complex logic, easy testing a different program may skip it

A sensible answer: use the CHECK constraint for the simple "never below zero" guarantee (it protects you from every program), and keep the larger "reserve stock for a basket for 15 minutes" logic in the application where it is easy to test. The shop and numbers are made up.

Common mistakes

  • Thinking a stored procedure is faster by magic. It saves round trips, but the work still costs the database machine something.
  • Putting all logic in the database "because it is safer" without tests or version control for it.
  • Using the same rule in both places and letting them drift apart.
  • Expecting SQLite to behave like a server database. It has no CALL and no saved procedures.

Key takeaways

  • A stored procedure is saved code you call; a stored function is saved code you use inside a query.
  • Benefits: one shared copy of a rule, fewer round trips and tighter control. Costs: harder testing, hidden logic, product lock-in and extra load on the database.
  • SQLite has no stored procedures: use an application routine in a transaction, or register a Python function for the connection.
  • Put simple "always true" rules in constraints; put complex, changing logic where you can test it.

Practice

1. What is the difference between a stored procedure and a stored function?

Show answer

A procedure is called to do a job (CALL name(...)); a function returns a value and is used inside a query.

2. Give two reasons a team might keep a rule in the database instead of the application.

Show answer

Any of: one shared copy for many programs, fewer network round trips, and being able to give users access to a procedure without access to the tables.

3. Give two reasons a team might avoid stored procedures.

Show answer

Any of: harder testing and version control, hidden logic, tied to one database product, and more work for the database machine.

4. In the transfer example, why did Rina's balance not change when the second transfer failed?

Show answer

Both UPDATE statements ran inside one with con: transaction. The CHECK failed on the second one, so the whole transaction was rolled back, including the first UPDATE.

5. Why must a program call create_function every time it connects?

Show answer

The function is not stored in the database file; it exists only for that connection.

6. A rule says "an order's total can never be negative". Where would you put it, and why?

Show answer

In a CHECK (total >= 0) constraint: it is simple, always true, and protects the data from every program.