BBampaa

Lessons › SQL › Deep Dive: Database Admin & ETL

SQL lesson

Stored procedures vs functions

Stored procedures run a sequence of actions - updates, deletions, branching logic - but don't return a value you can slot directly into a query.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Choosing Between Stored Procedures and Functions in Retail SQL

CALL mark_orders_shipped('2024-03-03');

SELECT order_id, revenue, revenue_tier(revenue) AS tier
FROM orders

Result:

order_idrevenuetier
O2001149.99Medium
O200289.5Low
O2003320.0High
O200455.75Low
O2005210.0High

Step by step

  1. CREATE PROCEDURE defines a reusable set of steps you can run with CALL.
    CREATE OR REPLACE PROCEDURE mark_orders_shipped(cutoff_date DATE)
    LANGUAGE plpgsql
    AS $$
    BEGIN
  2. UPDATE modifies existing rows in a table.
    CREATE OR REPLACE PROCEDURE mark_orders_shipped(cutoff_date DATE)
    LANGUAGE plpgsql
    AS $$
    BEGIN
    UPDATE orders
      SET status = 'shipped'
  3. WHERE keeps only the rows that match your condition.
    CREATE OR REPLACE PROCEDURE mark_orders_shipped(cutoff_date DATE)
    LANGUAGE plpgsql
    AS $$
    BEGIN
    UPDATE orders
      SET status = 'shipped'
    WHERE status = 'pending'
        AND order_date <= cutoff_date;
    END;
    $$;

Practice

Try each one in your head first, then open the answer.

1. Write a CREATE FUNCTION statement that defines a function called double_value taking an INT parameter n and returning n * 2 as INT.
CREATE OR REPLACE FUNCTION double_value(n INT) RETURNS INT AS $$ SELECT n * 2 $$ LANGUAGE SQL
2. Write a CREATE FUNCTION statement that defines a function called double_value taking an INT parameter n and returning n * 2 as INT.
CREATE OR REPLACE FUNCTION double_value(n INT) RETURNS INT AS $$ SELECT n * 2 $$ LANGUAGE SQL
3. Write a CREATE FUNCTION statement that defines a function called double_value taking an INT parameter n and returning n * 2 as INT.
CREATE OR REPLACE FUNCTION double_value(n INT) RETURNS INT AS $$ SELECT n * 2 $$ LANGUAGE SQL
4. Write a CREATE FUNCTION statement that defines a function called double_value taking an INT parameter n and returning n * 2 as INT.
CREATE OR REPLACE FUNCTION double_value(n INT) RETURNS INT AS $$ SELECT n * 2 $$ LANGUAGE SQL
5. Write a CREATE FUNCTION statement that defines a function called double_value taking an INT parameter n and returning n * 2 as INT.
CREATE OR REPLACE FUNCTION double_value(n INT) RETURNS INT AS $$ SELECT n * 2 $$ LANGUAGE SQL

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed