🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Dynamic SQL Safely: EXEC, Quoting, and Guard Rails

Advanced SQLAdvanced Techniques⭐ Premium

Why SQL has to be generated at all

Static SQL is a query the optimiser can parse, plan, cache, and secure once. Dynamic SQL is a query assembled at runtime, and it exists because some part of the statement cannot be known in advance: a table name chosen by a tenant, a pivot column list derived from data, a filter whose shape depends on which checkboxes a user selected. The moment a value becomes structure, the statement must be built.

The discipline that makes this safe is a single distinction applied without exception. Values are data and belong in parameters; identifiers are structure and belong in an allow-list checked against the catalogue. Almost every documented injection incident in a database comes from collapsing that distinction — concatenating a value into text because the API was awkward, or interpolating an identifier because quoting it seemed like enough. Escaping is a mitigation; separation is a guarantee.

By the end of this lesson you should be able to write dynamic statements whose values are always bound, whose identifiers are always validated, and whose text is logged before execution so a failure can be diagnosed rather than guessed at.

Values, identifiers, and expressions

Three categories of input reach a generated statement, and each has exactly one correct handling.

InputExampleCorrect handlingWrong handling
ValueCustomer id 4821Bind as a parameterConcatenate into text
IdentifierTable or column nameAllow-list against catalogue, then quoteConcatenate with ad-hoc escaping
Expression shapeSort direction, operatorMap to an enum of fixed tokensAccept arbitrary operator strings
SQL fragmentOptional predicatesBuild from known-safe templatesAccept user-supplied SQL
Data-derived pivot columnsMonth names found in dataGenerate, validate against pattern, quoteTrust raw column values

The expression row is the subtle one. Allowing a user to supply an operator such as greater than seems harmless until the field is a text box instead of a dropdown. Map input to a fixed set of tokens in code and never forward the raw string; the same applies to sort direction, where only ASC and DESC should ever reach the statement.

Parameterised EXEC that keeps values bound

The safe shape for dynamic statements in T-SQL separates the statement text, which contains placeholders, from the parameter list, which carries the values. Once values are parameters, they are never re-parsed as SQL, regardless of what they contain.

CREATE OR REPLACE PROCEDURE search_orders(
    p_customer_id bigint    = NULL,
    p_status      varchar   = NULL,
    p_min_amount  numeric   = NULL,
    p_sort_column varchar   = 'order_date',
    p_sort_dir    varchar   = 'DESC'
)
LANGUAGE plpgsql
AS $$
DECLARE
    v_sql   text;
    v_order text;
    v_where text := ' TRUE ';
BEGIN
    -- Expression input: map to fixed tokens, never forward the raw string
    IF upper(p_sort_dir) NOT IN ('ASC', 'DESC') THEN
        RAISE EXCEPTION 'sort direction must be ASC or DESC';
    END IF;
    v_order := format('ORDER BY %I %s',
                      CASE p_sort_column
                          WHEN 'order_date'  THEN 'order_date'
                          WHEN 'amount'      THEN 'amount'
                          WHEN 'customer_id' THEN 'customer_id'
                          ELSE 'order_date'
                      END,
                      upper(p_sort_dir));

    -- Optional predicates appended as literals; values stay bound
    IF p_customer_id IS NOT NULL THEN v_where := v_where || ' AND customer_id = $1 '; END IF;
    IF p_status      IS NOT NULL THEN v_where := v_where || ' AND status = $2 ';      END IF;
    IF p_min_amount  IS NOT NULL THEN v_where := v_where || ' AND amount  >= $3 ';     END IF;

    v_sql := format('SELECT order_id, order_date, amount, status
                       FROM orders
                      WHERE %s
                      %s
                      LIMIT 500', v_where, v_order);

    -- Log the shape before running it: this is what you will read at 03:00
    INSERT INTO sql_audit(statement_text, called_by, occurred_at)
         VALUES (v_sql, session_user, now());

    EXECUTE v_sql USING p_customer_id, p_status, p_min_amount;
END;
$$;

Note that format with %I is used only for the identifier, and only after the value has been matched against a known column set. %I quotes properly, but it is the allow-list that makes it safe; quoting alone would happily produce a correctly quoted reference to a table you never intended to expose. The audit insert before execution is the habit that turns a mysterious runtime failure into a reproducible statement.

Catalog-driven generation

The legitimate common case for dynamic SQL is when the database itself tells you the structure: a pivot whose columns come from the data, a maintenance job that acts on every table matching a pattern, or a permissions check that must consider every column a role can see.

-- PostgreSQL: build a count-per-status report from the data itself
DO $$
DECLARE
    v_cols text;
    v_sql  text;
BEGIN
    SELECT string_agg(format('%I', status), ', ' ORDER BY status)
      INTO v_cols
      FROM (SELECT DISTINCT status FROM orders WHERE status IS NOT NULL) s;

    IF v_cols IS NULL THEN
        RAISE NOTICE 'no statuses found, skipping';
        RETURN;
    END IF;

    v_sql := format(
        'SELECT customer_id, %s FROM orders GROUP BY customer_id',
        v_cols
    );

    RAISE NOTICE 'generated: %', v_sql;
    EXECUTE v_sql;
END;
$$;

-- Guard the generated identifiers with a pattern assertion
DO $$
DECLARE
    bad text;
BEGIN
    SELECT status INTO bad
      FROM orders
     WHERE status IS NOT NULL
       AND status !~ '^[A-Za-z0-9_]{1,30}$'
     LIMIT 1;

    IF bad IS NOT NULL THEN
        RAISE EXCEPTION 'status value % fails the identifier pattern; refusing to generate', bad;
    END IF;
END;
$$;

Two safety steps appear here and should appear in every generator. First, the generated text is emitted before execution, so an unexpected statement is visible in the log rather than only in its effects. Second, the data-derived identifier is validated against a pattern before it is ever quoted, because pattern validation rejects the cases where quoting would produce something syntactically valid yet semantically dangerous.

Guard rails: allow-lists, dry runs, and logging

Safety in dynamic SQL comes from layers, and each layer catches what the previous one missed. The allow-list prevents unknown identifiers from entering the statement. Parameter binding prevents values from becoming syntax. A statement log records what ran and who ran it. Optional dry-run or plan-only mode shows the effect before committing.

-- Identifier allow-list implemented as a table, not a case statement
CREATE TABLE permitted_identifiers (
    context   text NOT NULL,   -- 'sort_column', 'pivot_status', 'export_col'
    name      text NOT NULL,
    PRIMARY KEY (context, name)
);

INSERT INTO permitted_identifiers(context, name) VALUES
    ('sort_column', 'order_date'),
    ('sort_column', 'amount'),
    ('sort_column', 'customer_id');

-- Resolution refuses anything not explicitly granted
CREATE OR REPLACE FUNCTION resolve_identifier(p_context text, p_name text)
RETURNS text
LANGUAGE sql
STABLE
AS $$
    SELECT name
      FROM permitted_identifiers
     WHERE context = p_context
       AND name = p_name;
$$;

-- Caller behaviour when resolution fails
-- v_col := resolve_identifier('sort_column', p_sort);
-- IF v_col IS NULL THEN RAISE EXCEPTION 'column % is not queryable', p_sort; END IF;

Making the allow-list data means a review of who may query which columns becomes a row insert with an audit trail, rather than a code change buried in a case statement. It also makes the failure mode explicit: an unknown name resolves to nothing, and the caller decides whether to fail loudly — which is almost always the right answer, because a silent fallback to a default column hides a bug in the client.

Where dynamic SQL is unavoidable but expensive

Bulk transformations often need one statement per object: reindexing every partition, refreshing every materialized view, or updating statistics across a schema. The cost is round trips and plan churn, so generate in batches where the engine allows, run inside a maintenance window, and record per-object results so one failure does not abort the rest without explanation.

The other unavoidable case is multi-tenant systems where each tenant's data is physically separate. There, generate the statement from a template function that takes only the resolved tenant identifier, keep the template under version control, and assert that the resolved name appears in the catalogue before building text. If the tenant id does not exist as a real object, the correct behaviour is to fail, not to fall back to a default tenant.

💡Print before you run

Log or raise-notice the generated statement immediately before executing it. It costs one line, and it converts an unexplainable failure into a copy-pasteable reproduction — which is the difference between a ten-minute fix and an afternoon of guessing.

Common Mistakes

Concatenating values into statement text because binding felt awkward

Fix: Always bind values as parameters; only identifiers may be interpolated, and only after allow-listing

Trusting quoting to make an identifier safe

Fix: Resolve the name against an allow-list first; quoting handles syntax, not authorisation

Accepting sort direction or operators as free text

Fix: Map input to a fixed enum of tokens in code and reject anything outside it

Generating statements with no record of what ran

Fix: Write the statement and caller to an audit table before executing it

Best Practices

  • Keep the distinction between value and identifier in the function signature, not just in a comment
  • Store permitted identifiers in a reviewed table so access changes are data, not code
  • Validate data-derived identifiers against a pattern before quoting them
  • Log every generated statement with its caller, and expose plan-only mode for debugging
  • Fail closed when resolution returns nothing; silent defaults hide client bugs

Interview Questions

Q1: Why can you not parameterise a table name?

Parameters bind values, and an identifier is structure; the engine must know the object at parse time, so identifiers must be validated and interpolated.

Q2: What is the safest way to allow a user-chosen sort column?

Resolve the requested name against an allow-list, then quote the resolved result with the engine's identifier quoting.

Q3: How do you debug a dynamic statement that fails at runtime?

Log or print the exact generated text before execution and reproduce it manually with the same parameters.

Q4: Where does injection still slip through despite parameterisation?

In identifiers and expression fragments that were interpolated rather than bound or allow-listed.

Key Takeaways

  • Values are data and must be bound; identifiers are structure and must be allow-listed
  • Quoting fixes syntax, never authorisation — resolution against a catalogue comes first
  • Map free-form user input to fixed tokens instead of forwarding it
  • Log the generated statement before running it so failures are reproducible
  • Fail closed when an identifier cannot be resolved, and keep the allow-list in reviewed data
🔒

Premium Content

Dynamic SQL Safely: EXEC, Quoting, and Guard Rails

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement