views:

1551

answers:

1

Hi guys, 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.

+2  A: 

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));
Quassnoi
I am a idiot - why didn't i think about it?
DaNieL
Maybe you're overworked or stressed. No wonder, if you work with PgSQL.
analytik
Oh that was undeserved...it's no fault of PgSQL's that it can't read the developer's mind and insert `null` instead of `'null'`. Furthermore, from my own experience, PgSQL caused fewer problems than any other RDBMS I've worked with: MSSQL, MySQL, Oracle, Derby, SQLite, to name a few...
Tomislav Nakic-Alfirevic