in reply to Want DBI to load empty strings as NULL

You need to change Perl-false values to undef.

From DBI:

NULL Values

Undefined values, or undef, are used to indicate NULL values. You can insert and update columns with a NULL value as you would a non-NULL value. These examples insert and update the column age with a NULL value:

$sth = $dbh->prepare(qq{ INSERT INTO people (fullname, age) VALUES (?, ?) }); $sth->execute("Joe Bloggs", undef);

Later

What I failed to say was that the first sentence quoted above would have been better written as:

Undefined values, or undef, are THE ONLY WAY used to indicate NULL values.
SQL, for reasons better understood by by its creators than me, makes a huge distinction between NULL values and either empty strings or zero values. Because of this, a WHERE clause that needs to account for both has to jump through hoops like
WHERE ISNULL(age, xx) = ISNULL(?, xx)
or
$where_clause = defined $age? "age = ?" : "age IS NULL";
My guess is that due to that NULL vs '' distinction the DBI module intentionally does not treat '' or 0 as NULL.

Replies are listed 'Best First'.
Re^2: Want DBI to load empty strings as NULL
by dsheroh (Monsignor) on Feb 14, 2010 at 10:04 UTC
    My guess is that due to that NULL vs '' distinction the DBI module intentionally does not treat '' or 0 as NULL.
    I'd disagree slightly. Equating undef with NULL seems completely natural to me, as both of them mean "the value is either unknown or inapplicable". Both 0 and '' are known values, so they are neither undef nor NULL.

    The major difference between undef and NULL is just that perl takes the pragmatic course of assuming that the unknown is false, where SQL is strictly correct about it and insists that the truth of any expression depending on an unknown is also unknown.