in reply to DBI - Handling NULL values

As pg said, DBI uses undef to represent NULL values. This has two implications: 1) when you read a record that has NULLs, the values in the NULL fields will be undefined so if you want to print them, you'll need to change them to empty strings or a string like 'NULL' or 'UNKNOWN' or 'EMPTY' because you can't print undef, you can only print strings. However, 2) when you insert NULL values into the database, you insert undefs, not strings like 'NULL' or 'EMPTY'. DBI and the DBD will pass the undef to the RDBMS in a way that the RDBMS will be able to use its own internal reprsentation of NULLs. So this means that you turn the undef into a string before you print but that you leave the undef as undef when you insert.

A related issue is the difference between the SQL keyword NULL (which never has quotes around it) and the literal string 'NULL' which, because it has quotes around it, is a string value, not a NULL value. So:

This uses the SQL keyword NULL to insert a NULL into the table:

  $dbh->do("INSERT INTO x VALUES (1,NULL)");

But, this inserts the literal string N-U-L-L into the table: 

  $dbh->do("INSERT INTO x VALUES (1,'NULL')");

And when using placeholders.

This inserts a NULL value:

  $sth->execute(1,undef);

But this inserts the literal string N-U-L-L:
  
  $sth->execute(1,'NULL');
 

Replies are listed 'Best First'.
Re^2: DBI - Handling NULL values
by McDarren (Abbot) on Sep 29, 2005 at 07:03 UTC
    Yes, thanks
    It actually occurred to me soon after my original post that my initial code may not have been doing what I expected. I was going to test that but then I got the reply from [id://tanktalus] and got sidetracked.

    Your examples make it perfectly clear, and further demonstrate why it is much better practice to use placeholders and let DBI do all the dirty work.

    I'll be sure to remember that in future :)