How can I test for null and not null at the same time in sql?

蹲街弑〆低调 提交于 2019-12-13 08:56:08

问题


I have this sql:

select * from employees
where
lastname like '%smith%' and firstname like '%bob%' and middle like '%%'

The problem is the values of the name, particularly the middle name, can be null. So the statement above will find:

  smith, bob mike

but will not find

  smith, bob

because Bob's middle name is null (he has no middle name.)

I have this which works but I thought there was a better way and wanted input:

    select * from employees
    where
    lastname like '%smith%' 
    and firstname like '%bob%' 
    and (middle like '%%' or middle is null)

edit:

middle is not always blank. Sometimes it will have a value so I have to keep the test for middle name in. It could be populated or null.

Thanks. I am using Oracle 11g if that matters.


回答1:


You can use nvl:

select * from employees
where
lastname like '%smith%' and firstname like '%bob%' and nvl(middle,'') like '%%'

But this is just the same as not checking the middle name at all as like '%%' will match anything other than null.




回答2:


But

middle like '%%' or middle is null

is always true: either middle is null, in which case middle is null is true, or it contains one or more characters, in which case middle like '%%' is true. So you can just write:

select * from employees
where
lastname like '%smith%' and firstname like '%bob%'



回答3:


Maybe you can just drop the "middle" constraint from the query?
It seems like you don not really mind what it's value will be, so why not just:

select * from employees
where
lastname like '%smith%' and firstname like '%bob%'


来源:https://stackoverflow.com/questions/8535916/how-can-i-test-for-null-and-not-null-at-the-same-time-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!