Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make =NULL work in SQLite?

Tags:

c++

sql

sqlite

Given the following table:

Table: Comedians
=================

Id    First    Middle    Last
---  -------  --------  -------
 1     Bob      NULL     Sagat
 2    Jerry     Kal      Seinfeld      

I want to make the following prepared query:

SELECT * FROM Comedians WHERE Middle=?

work for all cases. It currently does not work for the case where I pass NULL via sqlite3_bind_null. I realize that the query to actually search for NULL values uses IS NULL, but that would mean that I cannot use the prepared query for all cases. I would actually have to change the query depending on the input, which largely defeats the purpose of the prepared query. How do I do this? Thanks!

like image 468
chacham15 Avatar asked Feb 01 '12 19:02

chacham15


People also ask

How do I allow NULL values in SQLite?

Syntax. Following is the basic syntax of using NULL while creating a table. SQLite> CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL );

Does SQLite support NULL?

Based on the SQL standard, PRIMARY KEY should always imply NOT NULL . However, SQLite allows NULL values in the PRIMARY KEY column except that a column is INTEGER PRIMARY KEY column or the table is a WITHOUT ROWID table or the column is defined as a NOT NULL column.

IS NOT NULL not working in SQLite?

In SQLite, Not Null Constraint is used to indicates that the column will not allow storing NULL values. Generally, in SQLite by default columns will allow NULL values in case if you have requirement like not to allow NULL values in column means then we need to add NOT NULL constraint on column.

How do I fix NULL in SQL?

The ISNULL Function is a built-in function to replace nulls with specified replacement values. To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value.


2 Answers

You can use the IS operator instead of =.

SELECT * FROM Comedians WHERE Middle IS ?
like image 153
dan04 Avatar answered Sep 21 '22 03:09

dan04


Nothing matches = NULL. The only way to check that is with IS NULL.

You can do a variety of things, but the straight forward one is...

WHERE
  middle = ?
  OR (middle IS NULL and ? IS NULL)

If there is a value you know NEVER appears, you can change that to...

WHERE
  COALESCE(middle, '-') = COALESCE(?, '-')

But you need a value that literally NEVER appears. Also, it obfuscates the use of indexes, but the OR version can often suck as well (I don't know how well SQLite treats it).

All things equal, I recommend the first version.

like image 26
MatBailie Avatar answered Sep 23 '22 03:09

MatBailie