Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not in operator in sql server not working

Tags:

sql

sql-server

I was solving hackerranks binary tree question.PFB the question

You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.

Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:

Root: If node is root node.
Leaf: If node is leaf node.
Inner: If node is neither root nor leaf node.

I was able to solve this using the below query

select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner' else 'Leaf'
end
from BST order by n

but before this, I was trying the below query which was not working

select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner'
 when p is not null and (n not in (select p from BST)) then 'Leaf'
end
from BST order by n

The above query was giving the root note and inner nodes but instead of leaf it was giving null, Can somebody please explain why is it showing this behaviour.

You can try the question here

Thankyou

like image 559
Shahzad Ahamad Avatar asked May 10 '18 04:05

Shahzad Ahamad


People also ask

How use not in condition in SQL Server?

The SQL Server NOT condition can be combined with the IN condition. For example: SELECT * FROM employees WHERE first_name NOT IN ( 'John', 'Dale', 'Susan' ); This SQL Server NOT example would return all rows from the employees table where the first_name is not 'John', 'Dale', or 'Susan'.

How does not in works in SQL?

The SQL Server NOT IN operator is used to replace a group of arguments using the <> (or !=) operator that are combined with an AND. It can make code easier to read and understand for SELECT, UPDATE or DELETE SQL commands. Generally, it will not change performance characteristics.

Is there a not operator in SQL?

The SQL NOT operatorNOT is a logical operator in SQL that you can put before any conditional statement to select rows for which that statement is false.

What can I use instead of not in SQL?

An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.


1 Answers

This is because of how sql treats IN and NOT IN query.

NOT IN evaluates to != clause for every element in the list and your list (column p) contains NULL value. Hence, value != NULL evaluates to UNKNOWN.

Duplicate: NOT IN clause and NULL values

Try this:

select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner'
 when p is not null and (n not in (select p from BST where p IS NOT null)) then 'Leaf'
end
from BST order by n

This should give the expected result.

like image 191
Rahul Jain Avatar answered Oct 22 '22 02:10

Rahul Jain