Pass Values into SQLite Queries and Scripts

SQLite queries can receive values without constructing SQL strings. Bind parameters when an application owns the connection. Use a temporary table when several statements in a plain SQL script need to share state. The SQLite shell also has its own parameter commands, which belong to the client rather than the SQL language.

These mechanisms solve different problems. A bound value is input to a statement. A temporary table is a real table associated with one connection. A shell parameter is implemented by the shell when it prepares a statement. None creates a general-purpose DECLARE variable in SQLite.

Choose the owner of the value

The two alternatives below select people with a score of at least 75. Each is complete and uses an in-memory database. Run either alternative independently. Both return Ada with 78 and Sam with 92, ordered by name.

Parameters represent values, so they cannot stand in for a table name, column name or SQL keyword. If an application lets a user choose a sort column, map that choice to an explicitly allowed SQL fragment. Continue binding the actual data values. SQLite parameter binding

💻Application

Bind parameters in application code

Save this as query_scores.py and run it with Python 3. The standard sqlite3 module supplies the binding API, so no additional database package is required.

Python
import sqlite3

connection = sqlite3.connect(":memory:")
try:
    connection.execute("CREATE TABLE Scores (Name TEXT, Points INTEGER)")
    connection.executemany(
        "INSERT INTO Scores VALUES (?, ?)",
        [("Ada", 78), ("Lin", 64), ("Sam", 92)],
    )
    rows = connection.execute(
        "SELECT Name, Points FROM Scores "
        "WHERE Points >= :minimum ORDER BY Name",
        {"minimum": 75},
    ).fetchall()
    print(rows)
finally:
    connection.close()

The output is [('Ada', 78), ('Sam', 92)]. The dictionary key omits the colon used in the SQL placeholder. Data is passed separately from SQL text. Keep that separation even when the input contains quotes or punctuation. The connection is explicitly closed because its context-manager transaction behavior does not itself close it. Python sqlite3 documentation

🗄️SQL script

Keep temporary state in a SQL script

Open a fresh in-memory connection with sqlite3 :memory: and execute the whole script in that connection.

SQL
CREATE TEMP TABLE QuerySettings (
    Singleton INTEGER PRIMARY KEY CHECK (Singleton = 1),
    MinimumScore INTEGER NOT NULL
);
INSERT INTO temp.QuerySettings VALUES (1, 75);

WITH Scores(Name, Points) AS (
    VALUES ('Ada', 78), ('Lin', 64), ('Sam', 92)
)
SELECT s.Name, s.Points
FROM Scores AS s
CROSS JOIN temp.QuerySettings AS settings
WHERE s.Points >= settings.MinimumScore
ORDER BY s.Name;

DROP TABLE temp.QuerySettings;

The singleton key permits at most one settings row, preventing accidental multiplication of result rows. The insert establishes that row before the query. An empty settings table would return no results. Explicit temp. qualification makes the intended storage clear. The table is connection-local and disappears when that connection closes, even if the final cleanup statement is not reached. Do not switch connections between script sections. SQLite CREATE TABLE

Use shell parameters only in the shell

In a separate sqlite3 :memory: session, these commands bind a value for subsequent shell queries:

SQL
.parameter init
.parameter set @minimum 75
SELECT @minimum, typeof(@minimum);
.parameter clear

The result is 75|integer with the shell's default output format. Dot commands are not SQL and cannot be sent through a database driver's execute method. The shell evaluates a .parameter set value as a SQL expression, so text quoting deserves attention. Do not build dot commands from untrusted input. In application code, use the driver's parameter API instead. SQLite shell parameters

Keep state narrow

Use a common table expression for a value needed by one statement, binding its inputs when necessary. Choose a temporary settings table only when its multi-statement lifetime is useful. There is no need to alter PRAGMA temp_store merely to simulate a variable, and storing secrets in a settings table does not make them inaccessible to the same connection.

This article revisits Herman Schoenfeld's temporary-table answer , recorded by Stack Overflow under CC BY-SA 4.0 . The examples and comparison here are newly written and add application binding and shell-specific boundaries.

Author: Herman Schoenfeld