Pergunta

  1. select field from table where field = 'value'
  2. select field from table where field in ('value')

The reason I'm asking is that the second version allow me to use the same syntax for null values, while in the first version I need to change the condition to 'where field is null'...

Foi útil?

Solução

When you are comparing a field to a null like field_name=NULL you are comparing to a known data type from a field say varchar to not only an unknown value but also an unknown data type as well, that is, for NULL values. When comparison like field_name=NULL again implies therefore a checking of data type for both and thus the two could not be compared even if the value of the field is actually NULL thus it will always result to false. However, using the IS NULL you are only comparing for the value itself without the implied comparison for data type thus it could result either to false or true depending on the actual value of the field.

See reference here regarding the issue of NULL in computer science and here in relation to the similarity to your question.

Now, for the IN clause (i.e. IN(NULL)) I don't know what RDBMS you are using because when I tried it with MS SQL and MySQL it results to nothing.

See MS SQL example and MySQL example.

Outras dicas

There is no difference in your example. The second, slightly longer, query is not usually used for a single value, it is usally seen for multiple values, such as

select field from table where field in ('value1', 'value2')

yes there is difference in both this queries. In first statment you can insert only 1 value in where clause "where field = 'value'" but in second statement in where field you can insert many values using IN clause "where field in (value1,value2..)" Examples:

1) select field from table where field ='value1';

2) select field from table where field in ('value1', 'value2')

To check null values

SELECT field
FROM tbl_name
WHERE 
(field IN ('value1', 'value2', 'value3') OR field IS NULL)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top