Returning varchars that are not null or empty SQL - 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,'') <> ''

Related

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

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.

Why Select eliminating NULL records on a varchar comparison

I have a table with 782,856 records. There is a column PEOPLE_TYPE in this table that is varchar(20). I don't think table schema matters but if it does I will gladly post it.
It has these distinct values (parens is a count of each type):
NULL (782,101)
ANONYMOUS (1)
BOARD (530)
USER (224)
So why does this select return these results???
select * from people where PEOPLE_TYPE != 'BOARD'
This return 225 rows...USER & ANONYMOUS....why aren't my nulls included...because I have now performed a text search and NULLs can't really be compared so they are eliminated?
Thank You for your patience with my remedial question.
NULL is a strange thing. Any comparison with NULL is false:
NULL = NULL is false
NULL != anything is false
NULL != NULL is also false.
You have to say things like column is null, or column is not null.
Your query would need
select * from people where PEOPLE_TYPE != 'BOARD' or PEOPLE_TYPE is null
You can read this for details on why records with NULL are not being returned: http://msdn.microsoft.com/en-us/library/ms188048.aspx
If you want records with NULL to be returned you need to write the query like this:
select * from people where ISNULL(PEOPLE_TYPE, '0') != 'BOARD'
Or this:
select * from people where PEOPLE_TYPE != 'BOARD' OR PEOPLE_TYPE IS NULL
There is another thing called COALESCE, http://msdn.microsoft.com/en-us/library/ms190349.aspx
I use quite often,
SELECT * FROM People WHERE COALESCE(PEOPLE_TYPE, '') != 'BOARD'

Rule out blank and null values in WHERE clause

Many times I have to run this query:
select * from users where name is not null and name != ''
Is there any better way to do this. I need more performance, any suggestion. I guess this is very common, so there may be some compiled function which will be something like
select * from users where name is present()
Using PostgreSQL 9 version.
For any x, null != x will be null and null is not true. That means that you can simply ignore NULLs in your case and say:
select * from users where name != ''
You could also convert NULLs to empty strings using COALESCE if that's clearer to you:
select * from users where coalesce(name, '') != ''
Of course that coalesce call isn't free.
Demo: http://sqlfiddle.com/#!2/e810c/2
You can use NULLIF:
SELECT *
FROM USERS
WHERE NULLIF(NAME,'') IS NOT NULL

Select rows where column is null

How do you write a SELECT statement that only returns rows where the value for a certain column is null?
Do you mean something like:
SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL
?
I'm not sure if this answers your question, but using the IS NULL construct, you can test whether any given scalar expression is NULL:
SELECT * FROM customers WHERE first_name IS NULL
On MS SQL Server, the ISNULL() function returns the first argument if it's not NULL, otherwise it returns the second. You can effectively use this to make sure a query always yields a value instead of NULL, e.g.:
SELECT ISNULL(column1, 'No value found') FROM mytable WHERE column2 = 23
Other DBMSes have similar functionality available.
If you want to know whether a column can be null (i.e., is defined to be nullable), without querying for actual data, you should look into information_schema.
Use Is Null
select * from tblName where clmnName is null
You want to know if the column is null
select * from foo where bar is null
If you want to check for some value not equal to something and the column also contains null values you will not get the columns with null in it
does not work:
select * from foo where bar <> 'value'
does work:
select * from foo where bar <> 'value' or bar is null
in Oracle (don't know on other DBMS) some people use this
select * from foo where NVL(bar,'n/a') <> 'value'
if I read the answer from tdammers correctly then in MS SQL Server this is like that
select * from foo where ISNULL(bar,'n/a') <> 'value'
in my opinion it is a bit of a hack and the moment 'value' becomes a variable the statement tends to become buggy if the variable contains 'n/a'.
select Column from Table where Column is null;
select * from tableName where columnName is null
For some reasons IS NULL may not work with some column data type. I was in need to get all the employees that their English full name is missing, I've used:
SELECT emp_id, Full_Name_Ar, Full_Name_En
FROM employees
WHERE Full_Name_En = '' or Full_Name_En is null

isnull vs is null

I have noticed a number of queries at work and on SO are using limitations in the form:
isnull(name,'') <> ''
Is there a particular reason why people do that and not the more terse
name is not null
Is it a legacy or a performance issue?
where isnull(name,'') <> ''
is equivalent to
where name is not null and name <> ''
which in turn is equivalent to
where name <> ''
(if name IS NULL that final expression would evaluate to unknown and the row not returned)
The use of the ISNULL pattern will result in a scan and is less efficient as can be seen in the below test.
SELECT ca.[name],
[number],
[type],
[low],
[high],
[status]
INTO TestTable
FROM [master].[dbo].[spt_values]
CROSS APPLY (SELECT [name]
UNION ALL
SELECT ''
UNION ALL
SELECT NULL) ca
CREATE NONCLUSTERED INDEX IX_TestTable ON dbo.TestTable(name)
GO
SELECT name FROM TestTable WHERE isnull(name,'') <> ''
SELECT name FROM TestTable WHERE name is not null and name <> ''
/*Can be simplified to just WHERE name <> '' */
Which should give you the execution plan you need.
is not null
Will only check if the field is not null. If the field contains an empty string, then the field is no longer null.
isnull(name, '') <> name
Checks for both a null and an empty string.
isnull(name,'') <> :name is shorthand for (name is null or name <> :name) (assuming that :name never contains the empty string, thus why shorthands like this can be bad).
Performance-wise, it depends. or statements in where clauses can give extremely bad performance. However, functions on columns impair index usage. As usual: profile.
isnull(name,'') <> name
Well I can see them using this because this way if the name doesn't match or is null it returns as a failed comparison. This really means: name is null or name <> name
Where as this one name is not null just checks to see if the name is null.
They don't mean the same thing.
name is not null
This checks for records where the name field is null
isnull(name,'') <> name
This one changes the value of null fields to the empty string so they can be used in a comparision. In SQL Server (but not in Oracle I think), if a value is null and it is used to compare equlaity or inequality it will not be considered becasue null means I don't know the value and thus is not an actual value. So if you want to make sure the null records are considered when doing the comparision, you need ISNULL or COALESCE(which is the ASCII STANDARD term to use as ISNULL doen't work in all databases).
What you should be looking at is the differnece between
isnull(a.name,'') <> b.name
a.name <> b.name
then you will understand why the ISNULL is needed to get correct results.
I apparently misread your question. So let me strike my first answer and try this one:
isnull(name,'') <> ''
is a misguided shortcut for
name is not null and name <> ''
Others have pointed out the functional difference. As to the performance issue, in Postgres I've found that -- oh, I should mention that Postgres has a function "coalesce" that is the equivalent of the "isnull" found in some other SQL dialects -- but in Postgres, saying
where coalesce(foobar,'')=''
is significantly faster than
where foobar is null or foobar=''
Also, it can be awesomely dramatically faster to say
where foobar>''
over
where foobar!=''
A greater than test can use the index and thus skip over all the blanks, while a not-equal test has to do a full file read. (Assuming you have an index on the field and no other index is used in preference.)
Also if you want to make use of the index on that column, use
name is not null and name <> ''
These two queries are not the same. For example, I do not have a middle name, this is a known fact, which can be stored as
MiddleName=''
However, if we don't know someone's middle name, we can store NULL.
So, ISNULL(MiddleName, '') means "persons without known middle names".
It is to handle both the empty string and NULL. While it is good to be able to do with with one statement, isnull is proprietary syntax. I would write this using portable Standard SQL as
NULLIF(name, '') IS NOT NULL