what's the difference between is not null and <>' ' - sql

Look my example, what's the difference between two codes?
Select name from customers where name is not null
Select name from customers where name <> ''

They do completely different things.
Select name from customers where name is not null
This one selects any customer who has a value in the name field. Those values can include '' as well as things like 'Sam', 'John Jones', 'pretty blonde girl'.
Select name from customers where name <> ''
This will select all names that are not null or blank In Sql Server at least. Other databases may handle this differently. The reason why it also excludes Null is that Null cannot be part of a comparison since it by definition means we don't have a clue what the value of this field is.
If you wanted to return both real names and null values and only exclude the empty strings. In SQl Server you would do:
Select name from customers where coalesce(name, 'Unknown') <>''

There are a lot of correct answers here but I think you are missing what NULL is. It's nothing so it's not comparable to anything. Here's some test for you
DECLARE #param CHAR(1)=NULL --you can replace #param with your column name in your queries
SELECT 1 WHERE #param = NULL --you can't compare NULL to anything using = > < <> != or any other comparision operator
SELECT 1 WHERE #param = '' --an empty value isn't the same as a NULL value so if a NULL is present it won't be returned
SELECT 1 where #param IS NULL --this is how you have to check for null values
--If you want to check for both empty and nulls, you can force the empty string with COALESCE or ISNULL
SELECT 1 WHERE COALESCE(#param,'') = ''
SELECT 1 WHERE ISNULL(#param,'') = ''

The key concept you are missing is that in SQL Server, NULL does not mean no value, it means that the value is unknown. So consider your query with some silly sample data:
DECLARE #t TABLE
( id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
, name VARCHAR(10) NULL );
INSERT INTO #t
VALUES
('dog'),
('cat'),
(''),
(NULL);
SELECT *
FROM #t
WHERE name <> '';
What you are asking the engine is to return the records where name is not an empty string. On the evaluation of the fourth record, it is determining if NULL equals empty string or not. NULL could be empty string, we don't know ... given that the value is unknown, the engine can't include that record because you are asking for only records where we know the name is definitely not empty string.
Consider another query against the same data:
WITH cteTemp AS
(
SELECT *
, isEqualToEmptyString = CASE WHEN name = '' THEN 'true' ELSE 'false' END
FROM #t
)
SELECT *
FROM cteTemp
WHERE isEqualToEmptyString = 'false';
Now this is written to demonstrate a point and there are cleaner ways to do the same thing (such as the COALESCE in HLGEM's answer.) But understand what is happening here: the query is first determining for sure what names are empty string (which excludes the NULL since its value is unknown) and then excluding those that are. Thus, the NULL is returned.

Null and empty string are two different things. A given field in a table can either have no value (null) or a value of an empty string (''). The results return by each query will be mutually exclusive.

Is not null determines if the object/record being inspected is a true null value or not (no data).
<> '' means is not an empty string, so the record does contain data (that there is an empty string) and is not actually null.
So a query with is not null will return records with a value of string.empty, and a query with <> '' will return values that are neither null nor empty. To catch both empty strings and null values you should use <> '' in your SQL statements.

Related

SQL Query to compare all the matching records

I want to assign Valid Column value to a Variable if the entire result set is valid. so need to write the SQL query that checks the entire result set if the column value is valid(not null and not empty) then assign first column value to that variable else check second column with same condition and assign to variable.
For Example: If my Table has column FirstName with 100 records, I need to check Whether all the records are valid(not null or not empty) records suppose 99th record is empty then I need to check LastName column and assign it to a variable.
Thanks in advance.
You can use CASE:
SELECT
CASE
WHEN FirstName IS NULL OR FirstName = '' THEN ISNULL(LastName, '')
ELSE FirstName END
FROM
Tbl
you can use If exists to determine if the column is valid:
if not exists (select 1 from table where col1 is null)
begin
select top(1) col1 from table
end

<> and != avoiding NULL in WHERE condition

I have a table PATIENT with Column STATUS. When I queried to get STATUS not equal to 1, I was expecting the result as NULL and 2.
But I am only getting 2 as the result. Can someone help me with this?
CREATE TABLE #PATIENT
(STATUS INT)
INSERT INTO #PATIENT (STATUS)
SELECT 1
UNION
SELECT 2
UNION
SELECT NULL
SELECT * FROM #PATIENT WHERE STATUS <> 1
When I queried with
SELECT * FROM #PATIENT WHERE ISNULL(STATUS, 0) != 1
I am able to get NULL and 2 as the result.
This is SQL SERVER 2012.
You can use OR in WHERE with Condition STATUS IS NULL .
SELECT * FROM #PATIENT WHERE STATUS <> 1 OR STATUS IS NULL
This will do it.
EDIT:
Conceptually, NULL means “a missing unknown value” and it is
treated somewhat differently from other values.
You cannot use arithmetic comparison operators such as =, <, or <>
to test for NULL
Because the result of any arithmetic comparison with NULL is also
NULL, you cannot obtain any meaningful results from such comparisons
we can not equate or not equate anything with null, thats why IS NULL
SELECT NULL <> 1 ===> NULL
Even though it is supposed to be true, it will return `NULL`
Hope this helps.
When you compare NULL value to any value then the result is always NULL.
So if you wan to select the NULL value as well then try this:
SELECT * FROM #PATIENT WHERE STATUS <> 1 OR STATUS IS NULL
DEMO
Conceptually "NULL" means a missing value. To test for NULL IS NULL or IS NOT NULL condition is used. Arithmetic operators cannot be used for comparing NULL values.
NULL<>1 :: returns false because NULL can be 1 or any other value (an unknown value).
Null is a special marker used in Structured Query Language (SQL) to indicate that a data value does not exist in the database.
And reason because you got only 2 and NOT NULL is because in SQL nothing is equal to NULL but also nothing is NOT equal to NULL.
In Simple words you cannot equate and not equate any value with NULL.

Returning varchars that are not null or empty SQL

I have a column in SQL that is varchar. I need it to return anything with a value.
Example...
select * from students where StudentID <> ''
Is this the correct way of doing it? I've tried is not null but then it returns anything that is empty as well.
Thanks
I would suggest using coalesce:
select * from students where coalesce(StudentID, '') <> ''
This will turn nulls into empty strings and disallow them. This has the added bonus of restricting empty strings as well.
A null is not equal to anything, not even another null, so a simple <> doesnt work.
select * from students where StudentID <> '' AND StudentID IS NOT NULL
You can target both white space and null.
There's something call NOT NULL
SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NOT NULL
Is that helping ?
try this:
select * from students where StudentID is not null
You have to handle the case that it's not null separately because you cannot compare with null-values. They are neither equal nor unequal to any other value(incl. null). NULL means "unknown value", so any comparison with any actual value makes no sense
....
WHERE StudentID IS NOT NULL AND StudentID <> ''
You could use ISNULL(StudentID,'') <> '' (or COALESCE). But i think this is more efficient.
Try using ISNULL()
select * from student where isnull(studentid,'') <> ''

How to display Items that equal a value in one column and are not null in another

Let's say I want to display all items in a table with following criteria how would i do this?
SELECT *
FROM TABLE
WHERE TABLE.COLUMN1 = 'example' AND TABLE.COLUMN2 != 'NULL'
I want it to display all values from COLUMN1. How does one go about this process in MS SQL?
NULL values can be compared using IS [NOT] NULL in SQL server. Please check this.
SELECT *
FROM TABLE
WHERE TABLE.COLUMN1 = 'example' AND TABLE.COLUMN2 IS NOT NULL
NULL is an UNKNOWN value , you cannot use any Comparison Operators (= , <> , > , <) with it. you check for nulls like
ColumnName IS NULL or ColumnName IS NOT NULL
If you think about it , it makes sense, to compare two or more values, you need to know the values only then you can compare them, Since SQL Server considers a NULL to be an UNKNOWN value, you cannot really compare an unknown value to anything.

Null Value Statement

I have created a table called table1 and it has 4 columns named Name,ID,Description and Date.
I have created them like Name varchar(50) null, ID int null,Description varchar(50) null, Date datetime null
I have inserted a record into the table1 having ID and Description values. So Now my table1 looks like this:
Name ID Description Date
Null 1 First Null
One of them asked me to modify the table such a way that The columns Name and Date should have Null values instead of Text Null. I don't know what is the difference between those
I mean can anyone explain me the difference between these select statements:
SELECT * FROM TABLE1
WHERE NAME IS NULL
SELECT * FROM TABLE1
WHERE NAME = 'NULL'
SELECT * FROM TABLE1
WHERE NAME = ' '
Can anyone explain me?
In a CREATE TABLE, the NULL or NOT NULL here varchar(50) null is a constraint that determines whether NULLs are allowed. NOT NULL means no.
When you inserted data, which statement did you run?
INSERT TABLE1 VALUES (Null, 1, First, Null)
or
INSERT TABLE1 VALUES ('Null', 1, First, 'Null')
The first one uses the keyword NULL, inserts a NULL (not a null value: no such thing, arguably). No values is stored except in the NULL bitmap fields
The second one has a string "null" and the characters N, U, L, L + 2 bytes for length are stored
When you run SELECT * FROM TABLE1, client tools will show NULL.
To test whether you actually have NULLs or the string NULL, run this
SELECT ISNULL(name, 'fish'), ISNULL(date, GETDATE()) FROM TABLE1
For the SELECTs
--null symbols. No value stored
SELECT * FROM TABLE1 WHERE NAME IS NULL
--string null
SELECT * FROM TABLE1 WHERE NAME = 'NULL'
--empty string
SELECT * FROM TABLE1 WHERE NAME = ' '
Note: null symbol/value is not empty string. It has no value and won't compare. Even to itself.
As for your DBA, the code above with ISNULL will decide what is stored.
Edit: if you are storing null symbol/value, then your DBA should read up on "null bitmap"
The data does represent nulls. The text 'Null' is your query tool displaying the text.
One of them asked me to modify the table such a way that The columns Name and Date should have Null values instead of Text Null. I don't know what is the difference between those.
The NULL keyword indicates the absence of any value -- the value is unknown.
But that won't stop someone from storing the letters that spell out "NULL", data type providing (which INT and DATETIME will not). Because of this, operators like IS NULL would not work on text that spells out "NULL" and vice versa -- searching for strings using: ... LIKE '%NULL%' will not return records with NULL values.
The data type of the column does matter with regard to NULL in SQL Server. In a UNION statement, you need to cast NULL to be the appropriate data type -- the default for NULL is INT:
SELECT CAST('2011-01-01 00:00:00' AS DATETIME)
UNION
SELECT CAST(NULL AS DATETIME)
Based on the information provided about the columns and the output, the DBA appears to be asking you to change the text the client you are using to connect to SQL Server with displays when a NULL value is encountered in a resultset. Reminds me of my first job dishwashing, and was asked to get the lefthanded spatula...
The string "Null" is a string.
The value of NULL (or Null or null, SQL is case-insensitive when it comes to these things) is used to denote an unknown value. It's the empty set of values, if you will.
http://www.w3schools.com/sql/sql_null_values.asp
NULL, in software, is symbolic of no value. Assuming you're inserting the columns using a string with null as the value, use the null constant. e.g.
INSERT INTO table1 (Name,ID,Description,Date) VALUES (NULL,1,'First',NULL);
Note that NULL is a constant in SQL, not the word "NULL" in a string.
AFAIC, there is no different between NULLs. There are different column types. But as long as a column is a text data type, and it's NULL, it's a text NULL.
Sometimes there are questions about empty strings ("") instead of NULLs, but the description you're using doesn't seem to be referring to that.
SELECT * FROM TABLE1 WHERE NAME IS NULL
Returns all rows where the Name is NULL
SELECT * FROM TABLE1 WHERE NAME = 'NULL'
Returns all rows where the Name is equal to the string 'NULL', Null values are not returned
SELECT * FROM TABLE1 WHERE NAME = ' '
Returns all rows where the Name is equal to exactly one space ' ', Null values are not returned
If you run this statement it might help clear up when its null and when its not
select
*,
case
WHEN name is null THEN 'Its Null alright'
ELSE 'It has a value'
END
FROM TABLE1