Parameterized Queries in SQL: Prevent SQL Injection Safely

Separate search values enter a protected database query while an injection threat is blocked

What You’ll Learn

In this lesson, you will learn how to safely pass user-supplied search values to SQL queries. You will use parameterized queries to search customer records without allowing input to change the meaning of the SQL statement.

  • Understand how SQL injection happens when values are concatenated into SQL.
  • Use placeholders with prepared statements.
  • Build safe partial-text searches with LIKE and ILIKE.
  • Recognize common mistakes when binding parameters.
Ad

The Concept

SQL injection occurs when an application combines untrusted user input with SQL source code. For example, an unsafe application might build a query by inserting a search box value directly into a string:

SELECT customer_id, full_name FROM customers WHERE full_name = 'user input';

If the input contains quote characters and additional SQL syntax, it may alter the query’s behavior. An attacker could potentially bypass filters, read unauthorized records, modify data, or damage the database.

A parameterized query keeps the SQL statement separate from its values. The query contains a placeholder, and the database driver sends the user-supplied value separately. The database then treats that value as data, not as SQL code.

This lesson uses PostgreSQL prepared-statement syntax, where placeholders are written as $1, $2, and so on. Application libraries use different placeholder styles, such as ? or named parameters, but the security principle is the same: bind values through the database API instead of concatenating them into SQL text.

Basic Example

Suppose a customer-support application has a search box. An agent enters part of a customer’s name or email address, and the application searches both columns. The following example creates sample data and prepares a safe search statement.

CREATE TEMP TABLE customers (
    customer_id integer,
    full_name text,
    email text
);

INSERT INTO customers (customer_id, full_name, email)
VALUES
    (101, 'Alice Morgan', 'alice.morgan@example.com'),
    (102, 'Malik Johnson', 'malik.johnson@example.com'),
    (103, 'Priya Shah', 'priya.shah@example.com');

PREPARE customer_search(text) AS
SELECT customer_id, full_name, email
FROM customers
WHERE full_name ILIKE '%' || $1 || '%'
   OR email ILIKE '%' || $1 || '%'
ORDER BY customer_id;

EXECUTE customer_search('ali');

Expected Output

The value ali matches “Alice” in the name and “malik” in the name.

 customer_id |   full_name    |             email
-------------+----------------+-------------------------------
         101 | Alice Morgan   | alice.morgan@example.com
         102 | Malik Johnson  | malik.johnson@example.com
(2 rows)

How the Code Works

A data-flow diagram shows a user search value entering an application, while fixed SQL with a placeholder is prepared separately. The application binds the value through the database API, the database combines the statement and value safely, and customer records are returned without treating the input as SQL code.
Parameterized queries keep SQL structure separate from user values: placeholders and database binding ensure search input is treated as data, not executable SQL.

PREPARE customer_search(text) defines a statement named customer_search. The text declaration says that this statement expects one text parameter.

The $1 token is the parameter placeholder. It is not replaced by copying characters into the SQL source. Instead, the value passed to EXECUTE is bound as a value.

The expression '%' || $1 || '%' creates a pattern that matches the search value anywhere in the text. ILIKE performs a case-insensitive comparison in PostgreSQL, so a search for ali can match both Alice and malik.

If an attacker submits a value such as ' OR 1=1 --, PostgreSQL still treats the entire input as the value of $1. It does not interpret the quote, Boolean expression, or comment marker as part of the SQL statement.

In a real application, the application database library normally prepares and executes the statement for you. The important pattern looks like this conceptually:

  • Write SQL with placeholders.
  • Pass values through the library’s parameter-binding method.
  • Never construct the SQL statement by concatenating user input.

Parameterized values protect data values, but they do not automatically make every part of a query safe. For example, a table name, column name, or sort direction usually cannot be supplied as an ordinary value parameter. If those parts must be selected dynamically, use an allowlist of known SQL identifiers and choices.

Another Example

Customer searches often include more than a text box. An application might let a support agent find customers who became active after a selected date. Both the date and the status should be parameters.

CREATE TEMP TABLE customer_accounts (
    customer_id integer,
    full_name text,
    account_status text,
    created_at date
);

INSERT INTO customer_accounts (customer_id, full_name, account_status, created_at)
VALUES
    (201, 'Jordan Lee', 'active', '2024-02-15'),
    (202, 'Elena Garcia', 'inactive', '2024-04-03'),
    (203, 'Marcus Brown', 'active', '2024-06-21');

PREPARE active_customer_search(date, text) AS
SELECT customer_id, full_name, account_status, created_at
FROM customer_accounts
WHERE created_at >= $1
  AND account_status = $2
ORDER BY created_at, customer_id;

EXECUTE active_customer_search('2024-05-01', 'active');

Here, the application supplies two values separately: a starting date and an account status. The SQL structure remains fixed, even if a user submits unexpected text for either value.

Common Mistakes

  • Concatenating the value before execution: Using a placeholder but then manually inserting the input into the SQL string defeats parameterization. Bind the value through the database driver’s parameter API.
  • Adding quotes around the placeholder: Write WHERE email = $1, not WHERE email = '$1'. The database driver handles value representation and quoting.
  • Using parameters for SQL identifiers: A value placeholder generally cannot safely stand for a table name or column name. Use a strict allowlist for selectable columns instead.
  • Assuming escaping is equivalent to parameterization: Hand-written escaping is easy to get wrong because rules differ by database, character encoding, and SQL context. Prefer the driver’s parameter-binding feature.
  • Forgetting wildcard behavior: In a LIKE search, user-supplied % and _ characters have wildcard meaning. Parameterization prevents SQL injection, but it does not automatically make those characters literal. If the search should treat them literally, escape them and use an ESCAPE clause according to your database’s rules.

Try It Yourself

Using the customers table from the first example, prepare a statement that searches only the email column. It should accept one text parameter and match email addresses case-insensitively. Execute it with the value example.com.

Your statement should use a placeholder and should not concatenate the search value into the SQL text.

Challenge

Create a parameterized customer lookup for a support dashboard. Use the customer_accounts table from the second example and prepare a statement that:

  • Accepts a minimum creation date and a customer name fragment.
  • Returns customers created on or after the supplied date.
  • Searches the name fragment with a case-insensitive partial match.
  • Orders results by creation date and then customer ID.
  • Executes with 2024-01-01 and the name fragment a.

Solution

CREATE TEMP TABLE customer_accounts (
    customer_id integer,
    full_name text,
    account_status text,
    created_at date
);

INSERT INTO customer_accounts (customer_id, full_name, account_status, created_at)
VALUES
    (301, 'Sarah Kim', 'active', '2023-12-18'),
    (302, 'Daniel Ortiz', 'active', '2024-01-12'),
    (303, 'Amara Wilson', 'inactive', '2024-03-09'),
    (304, 'Peter Novak', 'active', '2024-05-27');

PREPARE customer_name_search(date, text) AS
SELECT customer_id, full_name, account_status, created_at
FROM customer_accounts
WHERE created_at >= $1
  AND full_name ILIKE '%' || $2 || '%'
ORDER BY created_at, customer_id;

EXECUTE customer_name_search('2024-01-01', 'a');

The date is bound to $1, and the name fragment is bound to $2. The wildcard characters are part of the SQL expression, while the user’s fragment remains a separate value. This keeps the query structure fixed and prevents the supplied text from becoming executable SQL.

Key Takeaways

  • Parameterized queries keep SQL code separate from user-supplied values.
  • Use placeholders and bind values through the database driver or prepared-statement API.
  • Do not concatenate user input into SQL, even when the input comes from a search field.
  • Parameterization protects values, but dynamic identifiers and wildcard behavior require additional handling.
  • Prepared statements are useful for safe customer searches, filters, and other application queries.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad