Home / Learn Secure SQL / Stored Procedures Are Not Automatically Safe

Stored Procedures Are Not Automatically Safe

The same rule applies inside the database too.

Quick summaryThe same rule applies inside the database too.

How to think about this

Two kinds of stored procedurePlain parameters onlyFully safe, nothing dynamicinsideBuilds dynamic SQLinternallyNeeds its own parameterbinding for that dynamic part,same rules apply
Two kinds of stored procedure

Definition

Some stored procedures accept a parameter and then build a further query string internally (sometimes using EXECUTE/EXEC on dynamic SQL) using that parameter. If that internal building joins the parameter directly into text, the same code/data mixing problem exists inside the procedure.

Why you need this

Moving logic into the database does not, by itself, make it safe; it only moves where the same careful habits need to be applied.

How it works

Inside a procedure, use the database's own parameterised/prepared mechanism for any dynamic SQL it builds (e.g. sp_executesql with parameters in SQL Server, or EXECUTE ... USING in PostgreSQL), exactly as you would in application code.

Where you'll see this

  • Web application code review
  • Backend development
  • Database administration

SQLite has no stored procedures, so this is explained in reference form rather than run live.

A safely parameterised dynamic query inside a PostgreSQL function
CREATE OR REPLACE FUNCTION find_by_status(p_status TEXT)
RETURNS SETOF orders AS $$
BEGIN
  RETURN QUERY EXECUTE 'SELECT * FROM orders WHERE status = $1' USING p_status;
END;
$$ LANGUAGE plpgsql;

Test what you just read

1. A stored procedure that builds dynamic SQL internally...