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 →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| order_id | revenue | tier |
|---|---|---|
| O2001 | 149.99 | Medium |
| O2002 | 89.5 | Low |
| O2003 | 320.0 | High |
| O2004 | 55.75 | Low |
| O2005 | 210.0 | High |
Step by step
- 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 - 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' - 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
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 SQL2. 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 SQL3. 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 SQL4. 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 SQL5. 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 SQLLearn 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 →