Parameterised queries
- SQL course
- Expert
- Lesson 37/45
- 5 min
Use prepared statements.
Parameterized query
A parameterized query keeps the value separate from the SQL body. The $1 placeholder carries data safely; EXECUTE supplies the value.
PREPARE check_user(text) AS
SELECT * FROM users WHERE email = $1;
EXECUTE check_user('a@b.com');A parameterized query separates the value.
All columns are selected from users. WHERE keeps only the rows where email = $1 holds.
Parameterized query — details
The prepared plan is cached; repeated queries gain both speed and safety. The parameter count and types are set in PREPARE, values are given in order in EXECUTE.
Practice Parameterized query
Run the prepared check_user with the value 'a@b.com'.
Starter code
-- parameterized query
EXECUTESample solution
EXECUTE check_user('a@b.com');Expected output
id email name 1 a@b.com Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Execute the query
____ check_user('a@b.com');
EXECUTE check_user('a@b.com');
Explanation: EXECUTE is the right answer.
2 What does $1 represent?
- The table name
- An index name
- A parameter placeholder Correct answer
- The column name
Explanation: $1 is a parameter placeholder.
3 Parameterised queries: match the terms
| Term | Meaning |
|---|---|
parameter |
parameter |
placeholder |
placeholder |
EXECUTE |
execute |
cache |
cache |