Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is my banana? (SQL Query NULL issue)

I have this table:

CREATE TABLE [dbo].[Fruit](
    [RecId] [int] IDENTITY(1,1) NOT NULL,
    [Banana] [int] NULL,
    [TextValue] [varchar](50) NULL
)

And the following piece of code:

DECLARE @FruitInput INT = NULL
SELECT * FROM Fruit WHERE Banana = @FruitInput 

This record is in that table:

1|NULL|Hello 

Why wont my query return this record?

like image 297
Tys Avatar asked Nov 06 '13 14:11

Tys


People also ask

How do you handle NULL in SQL?

Handling SQL NULL values with Functions ISNULL(): The ISNULL() function takes two parameters and it enables us to replace NULL values with a specified value. The expression parameter indicates the expression which we want to check NULL values.

How do I remove a NULL row in SQL query?

Use the delete command to delete blank rows in MySQL. delete from yourTableName where yourColumnName=' ' OR yourColumnName IS NULL; The above syntax will delete blank rows as well as NULL row.

How do I remove a NULL column in SQL query?

To exclude the null values from the table we need to use IS NOT NULL operator with the WHERE clause. WHERE Clause: The WHERE clause is used to filter the records. It will extract those records that fulfill the condition.


1 Answers

It is because Null is undefined. Null neither equal nor not equal to anything. Please read more on MSDN.

Null values can be checked with is null (or is not null), or isnull() or coalesce() functions depending on the requirement.

Try this:

SELECT * FROM Fruit WHERE Banana is null

And following query to select all the records in case if @FruitInput is null:

SELECT * FROM Fruit WHERE @FruitInput is null or Banana = @FruitInput
like image 178
Kaf Avatar answered Nov 06 '22 08:11

Kaf