<> operator in SQL - sql

I have a table like this
ID Name IsDeleted
1 Yogesh Null
2 Goldy 1
Now when I run this query
select *
from tableName
where IsDeleted <> 1
I should get ID 1 record, But I am not getting it,
But when I run this
select *
from tableName
where IsDeleted is null
I get ID 1 record,
Why am I facing this behavior ??
Isn't NULL <> 1 is a true statement in SQL ??
IsDeleted is a bit type field with Allow Null true

select * from table
where COALESCE(IsDeleted, 0) <> 1
-- or ISNULL instead of COALESCE.
--ISNULL seems to be better in subqueries, but it's not ANSI SQL.
or
select * from table
where IsDeleted <> 1 or IsDeleted IS NULL

Comparing something with null will always result in unknown. That is why you need to use the is operator to compare null or use functions like COALESCE or isnull to replace null

select *
from tableName
where isnull(IsDeleted,0) <> 1

you compare different types. in this case its an other type (unknown) and not comparable
use the or statement to compare each type seperate
WHERE IsDeleted <> 1 OR IsDeleted is null

Learn about NULL - a comparison with NULL (in standard SQL) yields UNKNOWN, which is not true nor false (and the reason why your expectation is not met).
Try this:
PRINT CASE
WHEN 1 = NULL THEN '1 = NULL'
WHEN 1 <> NULL THEN '1 <> NULL'
ELSE '1 is neither = NULL nor <> NULL'
END
You can either first make sure that you don't have a NULL value (for instance by using the ISNULL or COALESCE functions), or use a condition with the operator IS NULL or IS NOT NULL.

Normal practice would dictate that if you had a column that essentially was a true false, yes no type of field then you should use a bit field with the default value set to 0.
So in your case above you could just run this:
select *
from tableName
where IsDeleted = 0
But in answer to your above question, if the Null is a true NULL value in the table then this will work for you:
select *
from tableName
where IsDeleted is null
or
select *
from tableName
where isnull(IsDeleted,0) = 0
to get record 1 and
select *
from tableName
where IsDeleted is not null
to get record 2
Good luck
Paul.

Related

SQL ISNULL not working

I'm trying to display 00001 when the query result is null but the query still return null. I don't know whats wrong with my query.
EDIT:
Assuming OBRNo is 123-5678-10-13-1619 means LEN(a.OBRNo) is 19
SELECT TOP 1 CASE WHEN RIGHT(a.OBRNo, 5) = NULL THEN '00001' ELSE a.OBRNo
END as CaseWhen,
ISNULL(a.OBRNo, '00001') as ISNULL,
RIGHT(OBRNo, 5) as OrderBy
FROM tbl_T_BMSCurrentControl as a
WHERE LEN(a.OBRNo) = 20 and a.ActionCode = 1
ORDER BY OrderBy DESC
Compare with NULL with IS NULL / IS NOT NULL, not with = NULL.
SELECT TOP 1 CASE WHEN RIGHT(a.OBRNo, 5) IS NULL THEN '00001' ELSE a.OBRNo END
...
You could change this behaviour with SET ANSI_NULLS.
The reason why you can't compare with = by default is: NULL means undefined. Nothing is equal to unknown not even NULL. If you compare with NULL the result is unknown, hence also NULL.
Is your query returning any row?
Your ISNULL (x,y) should do what you expect but it looks like your WHERE is filtering all the records, due to the NULLS.
Try this:
SELECT TOP 1 CASE WHEN RIGHT(a.OBRNo, 5) = NULL THEN '00001' ELSE a.OBRNo
END as CaseWhen,
ISNULL(a.OBRNo, '00001') as ISNULL,
RIGHT(OBRNo, 5) as OrderBy
FROM tbl_T_BMSCurrentControl as a
WHERE (a.OBRNo IS NULL OR LEN(a.OBRNo) = 20) and a.ActionCode = 1
ORDER BY OrderBy DESC
LEN(a.OBRNo) being a.OBRNo NULL will be NULL so NULL = 20 will be NULL and NULL AND a.ActionCode = 1 will be NULL which when filtering is treated as FALSE

How to check if all rows validate a predicate

I've a table in my database for which I need to check if all rows have one field not null.
If there are no row or if there is at least 1 row with the field null => true
If there are rows and they are all with the field not null => False
Is there a way to do this in on simple query? Or I need to check if my table is empty first then if it's not check if I've a row with the field value empty ?
This will count how many NULL values you have in a field;
SELECT
SUM(CASE WHEN FieldName IS NULL THEN 1 ELSE 0 END) NullValues
FROM TableName
Will return 0 if there are no NULL values, and will return the number of NULLS if there are any present.
If you actually want to return a value as 'True' or 'False' then do this;
SELECT CASE
WHEN a.NullValues > 0
THEN 'True'
ELSE 'False'
END CheckField
FROM (
SELECT
SUM(CASE WHEN FieldName IS NULL
THEN 1
ELSE 0
END) NullValues
FROM TableName
) a
Use count(*) and count(field) and compare the two:
select
case when count(*) > 0 and count(*) = count(field) then 1 -- not empty and no nulls
else 0 end as isgood
from mytable;
Oracle SQL has no boolean data type , so I use 1 for true and 0 for false. You can replace this with whatever you like (e.g. 'true' instead of 1 and 'false' instead of 0).
As to turning this into a predicate (correlated to a main query), you'd use something along the lines of:
select ...
from main
where exists
(
select 1
from mytable
where mytable.colx = main.coly
having count(*) > 0 and count(*) = count(field)
);
You can do this with aggregation. However, it is difficult to understand what you are asking for. If you want to check that a field has no NULL values, you can do:
select (case when count(*) > 0 then 1 else 0 end) as HasNullValues
from t
where field is null;
Alternate way I found using max with putting null first:
select case when
max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1
else 0 end as flag
from MYTABLE;

If value return the value. If a record not exists or when column is null, return 0 in Sql Server - different ways

I want to return 0 if there is no record or if the Column1 is null.
select #var = Column1
from myschema.mytable
where Id = #suppliedId;
select isnull(#var, 0);
The above code outputs 0 if if Column1 is null. Or if a row is not found
Whereas I tried to save some keystrokes but it resulted in,
select isnull(Column1, 0)
from myschema.mytable
where Id = #suppliedId;
The above code outputs null if Column1 is null or when there is no row
Any ideas what is wrong here ? Or is there any shorter way of writing the first code ?
You can do
SELECT #var = ISNULL(MAX(Column1), 0)
FROM myschema.mytable
WHERE Id = #suppliedId;
A scalar aggregate always returns a single row even if the underlying query returns zero rows.
Not really saving key strokes, but something like this could help :-)
SELECT TOP 1 tbl.field
FROM
(
SELECT 0 AS inx, 'no record' AS field
--if only one row is possible, than set '1' literally
UNION SELECT ROW_NUMBER() OVER(ORDER BY mytable.orderfield), ISNULL(mytable.Land,'is null')
FROM mytable
WHERE IDENTITY = #suppliedID
) AS tbl
ORDER BY tbl.inx DESC

Case when statement in SQL

I am using the following query. In this query I want to apply the where clause based on passed parameter. But the issue is that where clause is like 'value = if parameterVal = 'I' than NULL else NOT NULL'
I've build a query like this
SELECT * FROM MASTER
WHERE
Column1 IS (CASE WHEN :Filter = 'I' THEN 'NULL' ELSE 'NOT NULL' END)
but it's not working. Help me solve this.
UPDATE
Updating question to elaborate question more clearly.
I've one table MASTER. Now I am passing one parameter in query that is Filter (indicated by :Filter in query).
Now when the Filter parameter's value is 'I' than it should return the following result.
SELECT * FROM MASTER WHERE Column1 IS NULL
but if the passed argument is not equal to 'I' than,
SELECT * FROM MASTER WHERE Column1 IS NOT NULL
SELECT * FROM MASTER
WHERE (Filter = 'I' AND Column1 IS NULL)
OR
(Filter <> 'I' AND Column1 IS NOT NULL)
If you really insist on using a CASE the SELECT could be rewritten as:
SELECT *
FROM MASTER
WHERE CASE
WHEN COLUMN1 IS NULL AND FILTER = 'I' THEN 1
WHEN COLUMN1 IS NOT NULL AND FILTER <> 'I' THEN 1
ELSE 0
END = 1
SQLFiddle here
Frankly, though, I think that this is very difficult to interpret, and I suggest that #MAli's version is better.
Your case has assignment not equality check

SQL if statement debugging

I have the following two queries, The first one works as you would expect. The second raises an exception saying invalid column name ISDELETED. BUT I've added the if else structure precisely to avoid that error, what am i doing wrong On the second query
IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL
select 1
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
select 0
ELSE SELECT -1
And
IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL
select Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0
ELSE SELECT -1
Before run the query DB Engine try to validate your code, but not validate your logic. If your table hasn't ISDELETED column DB shows you an error. So you have to hide from DB Engine your wrong code as dynamic sql. Dynamic sql will not be validate.
IF COL_LENGTH('vwAs', 'IsActive') IS NOT NULL
select Count(*) [vwB] from [vwAs] WHERE ISACTIVE = 1
ELSE IF COL_LENGTH('vwABCs', 'IsDeleted') IS NOT NULL
exec('select Count(*) [vwABCsActive] from [vwABCs] WHERE ISDELETED = 0')
ELSE SELECT -1