Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unusual sql server query result

Let's say I have a table called nameAge:

ID  Name  Age
1   X     12
2   Y     12
3   null  null
4   Z     12

and when I run a query like:

select * from nameAge where Age <> 12

it returns me an empty result set while I have row with id 3 where age is different than null?

Using Sql Server 2008 R2.

Any ideas?

Edit: Possibility to be duplicate with suggested answer may be at one point but does not cover at all and it shows how to use null values when compared with null but what I wanted to ask was about the result set which includes null values

like image 515
canpoint Avatar asked Jun 02 '15 06:06

canpoint


People also ask

How do I get unique results in SQL?

SELECT DISTINCT returns only unique values (without duplicates). DISTINCT operates on a single column. DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.

What is unique record in SQL?

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.

How do you handle special characters in SQL?

How do you handle special characters in SQL query? Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence.

Is there a unique function in SQL?

The UNIQUE keyword in SQL plays the role of a database constraint; it ensures there are no duplicate values stored in a particular column or a set of columns.


1 Answers

This is the intended behavior. You cannot compare NULL values using = or <>. You have to use IS NULL or IS NOT NULL.

If you want NULL values only use IS NULL:

select * from nameAge where age IS NULL

If you want NULL values with age <> 12 values, use:

select * from nameAge where age <> 12 OR age IS NULL
like image 118
ughai Avatar answered Nov 12 '22 23:11

ughai