Postgresql: using 'NULL' value when insert and update rows with prepared statements


sometimes i need to insert into the table some null values, or update them setting the value to NULL.

I've read somewhere in the postgresql documentation that this cant be done, but can be tricket with the default value:

pg_query("INSERT INTO my_table (col_a, col_b) VALUES ('whatever', default)

p.s: i know that in this example i'll have the same result with

pg_query("INSERT INTO my_table (col_a) VALUES ('whatever')

But the problems comes witht the prepared statements:

pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, default)");
pg_exec($pgconn, 'insert_null_val', array('whatever'));
//this works, but
pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', 'NULL'));
//insert into the table the string 'NULL'.
//instead using array('whatever', '') it assume the col_b as empty value, not NULL.

The same problem comes with the update query.

I think there is a solution, becose pgmyadmin can do that (or seem like it can), and is written i php (i dont think it doesnt use the prepared statements anyway)

If youre wondering why i need to paly with null values in my tables, let me throw an example (maybe there is a way better then the null value): assume i have the user table, and the email col: this one can be empty, but is a unique index.. 2 empty email are equal and violates the unique constraint, while 2 NULL values are not equal and can coexist.

6/22/2009 2:27:05 PM

Accepted Answer

Use the php's literal NULL as a parameter:

pg_prepare($pgconn, 'insert_null_val', "INSERT INTO my_table (col_a, col_b) VALUES ($1, $2)");
pg_exec($pgconn, 'insert_null_val', array('whatever', NULL));
6/22/2009 2:33:42 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow