Search code examples
postgresqlnpgsql

What is the difference between prepared statement and parameterized query in Npgsql?


I'd like to get clarification on whether parameterized queries are the same as prepared statements in Npgsql. If I write the following, without an explicit cmd.Prepare():

var cmd = new NpgsqlCommand("UPDATE foo SET bar=@bar;");
cmd.Parameters.Add("bar", 1);
cmd.ExecuteNonQuery();

Without considering the effects of automatic preparation, is the above a prepared statement internally? Conversely, if automatic preparation takes effect, does it apply to all queries regardless of whether it is parameterized?


Solution

  • No, they are two completely orthogonal things. Parameterizing is about extracting values out of the SQL, replacing them with a placeholder (@bar) which refers to the data out-of-band. This protects against SQL injection, and also transfers the data in a more efficient binary format, rather than encoding it as a string within the SQL.

    Prepared statements are about preparing a SQL once, and then reusing the same prepared statement to avoid the overhead of the database parsing and planning the SQL each time.

    Without considering the effects of automatic preparation, is the above a prepared statement internally?

    Without automatic preparation, this query executes unprepared, even though it has parameters.

    Conversely, if automatic preparation takes effect, does it apply to all queries regardless of whether it is parameterized?

    Yes - queries without any parameters can also get prepared. This is beneficial since a query may be complex to parse/plan regardless of whether it has parameters or not.