Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare values which may both be null in T-SQL

I want to make sure I'm not inserting a duplicate row into my table (e.g. only primary key different). All my fields allow NULLS as I've decided null to mean "all values". Because of nulls, the following statement in my stored procedure can't work:

IF EXISTS(SELECT * FROM MY_TABLE WHERE      MY_FIELD1 = @IN_MY_FIELD1  AND     MY_FIELD2 = @IN_MY_FIELD2  AND     MY_FIELD3 = @IN_MY_FIELD3  AND      MY_FIELD4 = @IN_MY_FIELD4  AND     MY_FIELD5 = @IN_MY_FIELD5  AND     MY_FIELD6 = @IN_MY_FIELD6)     BEGIN         goto on_duplicate     END 

since NULL = NULL is not true.

How can I check for the duplicates without having an IF IS NULL statement for every column?

like image 794
srmark Avatar asked Jul 02 '09 15:07

srmark


People also ask

Can we compare two NULL values in SQL?

SQL has the is [not] null predicate to test if a particular value is null . With is [not] distinct from SQL also provides a comparison operator that treats two null values as the same. Note that you have to use the negated form with not to arrive at similar logic to the equals ( = ) operator.

How do I compare two columns with NULL values in SQL?

Use <=> (null-safe equality operator) negated comparison which returns FALSE in case one of the operands is null but TRUE when both are null and both operands have equal non-null values.

Can two NULL values be compared?

The value NULL does not equal zero (0), nor does it equal a space (' '). Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.

What would be the result if the two NULL values were compared?

Because null is considered to be unknown, two null values compared to each other are not considered to be equal. In expressions using arithmetic operators, if any of the operands is null, the result is null as well.


2 Answers

Along the same lines as @Eric's answer, but without using a 'NULL' symbol.

(Field1 = Field2) OR (ISNULL(Field1, Field2) IS NULL) 

This will be true only if both values are non-NULL, and equal each other, or both values are NULL

like image 181
Graeme Job Avatar answered Oct 19 '22 12:10

Graeme Job


Use INTERSECT operator.

It's NULL-sensitive and efficient if you have a composite index on all your fields:

IF      EXISTS         (         SELECT  MY_FIELD1, MY_FIELD2, MY_FIELD3, MY_FIELD4, MY_FIELD5, MY_FIELD6         FROM    MY_TABLE         INTERSECT         SELECT  @IN_MY_FIELD1, @IN_MY_FIELD2, @IN_MY_FIELD3, @IN_MY_FIELD4, @IN_MY_FIELD5, @IN_MY_FIELD6         ) BEGIN         goto on_duplicate END 

Note that if you create a UNIQUE index on your fields, your life will be much simpler.

like image 23
Quassnoi Avatar answered Oct 19 '22 13:10

Quassnoi