Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java DB2 JDBC: How can one use null parameters in a WHERE clause for a SELECT statement where the value can be either null or not null?

For example I have the following select query for a PreparedStatement:

"SELECT FOO FROM BAR WHERE FOOBAR=?"

The parameter for FOOBAR can have a value and it could also be null.

Would the following code work?

if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, null);

If not, how should this be handled?

like image 430
heisenbergman Avatar asked Jul 15 '13 07:07

heisenbergman


People also ask

Is NULL in DB2 WHERE clause?

The IS NULL condition is satisfied if the column contains a null value or if the expression cannot be evaluated because it contains one or more null values. If you use the IS NOT NULL operator, the condition is satisfied when the operand is column value that is not null, or an expression that does not evaluate to null.

How do you handle a NULL in DB2 query?

A null value is a special value that Db2 interprets to mean that no data is present. If you do not specify otherwise,Db2 allows any column to contain null values. Users can create rows in the table without providing a value for the column. Using the NOT NULL clause enables you to disallow null values in the column.

How does Jdbc handle NULL values while working?

Avoid using getXXX( ) methods that return primitive data types. Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null.

How do you handle NULL values in a database?

By using the assignment operator (“=”), you can set any value of a column to NULL by using the Update Statement.


2 Answers

It won't work, null has no equivalence. If you're using a PreparedStatement, try this:

if(<condition>) preparedStatement.setObject(1, "<string value>");
else preparedStatement.setNull(1, Types.VARCHAR);

It will send the null as an IN parameter.

like image 98
Mark M Avatar answered Oct 21 '22 01:10

Mark M


As per SQL standard, if a column has a NULL value, the search condition to check if it has NULL value is "column IS NULL". If column does not have null value you can have condition such as "column = 'blabla'. To make parameter markers work in both cases, change the statement as following:

SELECT FOO FROM BAR WHERE COALESCE(FOOBAR, 'a') = ? "

and have the following code:

if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, "a");

Whatever @Mark suggested did not work for me on Oracle.

like image 34
mvsagar Avatar answered Oct 21 '22 00:10

mvsagar