Let's say that the record comes from a form to gather name and address information. Line 2 of the address will typically be blank if the user doesn't live in apartment. An empty string in this case is perfectly valid. I tend to prefer to use NULL to mean that the value is unknown or not given.
I don't believe the physical storage difference is worth worrying about in practice. As database administrators, we have much bigger fish to fry!
Answer from Larry Coleman on Stack ExchangeLet's say that the record comes from a form to gather name and address information. Line 2 of the address will typically be blank if the user doesn't live in apartment. An empty string in this case is perfectly valid. I tend to prefer to use NULL to mean that the value is unknown or not given.
I don't believe the physical storage difference is worth worrying about in practice. As database administrators, we have much bigger fish to fry!
I do not know about MySQL and PostgreSQL, but let me treat this a bit generally.
There is one DBMS namely Oracle which doesn't allow to choose it's users between NULL and ''. This clearly demonstrates that it is not necessary to distinguish between both. There are some annoying consequences:
You set a varchar2 to an empty string like this:
Update mytable set varchar_col = '';
the following leads to the same result
Update mytable set varchar_col = NULL;
But to select the columns where the value is empty or NULL, you have to use
select * from mytable where varchar_col is NULL;
Using
select * from mytable where varchar_col = '';
is syntactically correct, but it never returns a row.
On the other side, when concatenating strings in Oracle. NULL varchars are treated as empty strings.
select NULL || 'abc' from DUAL;
yields abc. Other DBMS would return NULL in these cases.
When you want to express explicitly, that a value is assigned, you have to use something like ' '.
And you have to worry whether trimming not empty results in NULL
select case when ltrim(' ') is null then 'null' else 'not null' end from dual
It does.
Now looking at DBMS where '' is not identical to NULL (e.g. SQL-Server)
Working with '' is generally easier and in most case there is no practical need to distinguish between both. One of the exceptions I know, is when your column represents some setting and you have not empty defaults for them. When you can distinguish between '' and NULL you are able to express that your setting is empty and avoid that the default applies.
java - Get empty string when null - Stack Overflow
Use "+ string.Empty" or "?.ToString() ?? string.Empty" for a nullable object
Null is converted to empty string when writing to database.
Replace empty string to null in form submit, and JS limitation in Changeset Object
String s1 = ""; means that the empty String is assigned to s1.
In this case, s1.length() is the same as "".length(), which will yield 0 as expected.
String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
Null means nothing. Its just a literal. Null is the value of reference variable. But empty string is blank.It gives the length=0. Empty string is a blank value,means the string does not have any thing.
You can use Objects.toString() (standard in Java 7):
Objects.toString(gearBox, "")
Objects.toString(id, "")
From the linked documentation:
public static String toString(Object o, String nullDefault)Returns the result of calling
toStringon the first argument if the first argument is not null and returns the second argument otherwise.Parameters:
o- an object
nullDefault- string to return if the first argument isnullReturns:
the result of callingtoStringon the first argument if it is notnulland the second argument otherwise.See Also:
toString(Object)
For java 8 you can use Optional approach:
Optional.ofNullable(gearBox).orElse("");
Optional.ofNullable(id).orElse("");
The Title basically says it all. If an object is not null, calling ".ToString()" is generally considered better than "+ string.Empty", but what about if the object could be null and you want a default empty string.
To me, saying this
void Stuff(MyObject? abc)
{
...
string s = abc?.ToString() ?? string.Empty;
...
}is much more complex than
void Stuff(MyObject? abc)
{
...
string s = abc + string.Empty;
}The 2nd form seems to be better than the 1st, especially if you have a lot of them.
Thoughts?
----
On a side note, something I found out was if I do this:
string s = myNullableString + "";
is the same thing as this
string s = myNullableString ?? "";
Which makes another branch condition. I'm all for unit testing correctly, but defaulting to empty string instead of null shouldn't really add another test.
using string.Empty instead of "" is the same as this:
string s = string.Concat(text, string.Empty);
So even though it's potentially a little more, I feel it's better as there isn't an extra branch test.
EDIT: the top code is an over simplification. We have a lot of data mapping that we need to do and a lot of it is nullable stuff going to non-nullable stuff, and there can be dozens (or a lot more) of fields to populate.
There could be multiple nullable object types that need to be converted to strings, and having this seems like a lot of extra code:
Mydata d = new()
{
nonNullableField = x.oneField?.ToString() ?? string.Empty,
anotherNonNullableField = x.anotherField?.ToString() ?? string.Empty,
moreOfThesame = x.aCompletelyDifferentField?.ToString() ?? string.Empty,
...
}vs
Mydata d = new()
{
nonNullableField= x.oneField + string.Empty, // or + ""
anotherNonNullableField= x.anotherField + string.Empty,
moreOfThesame = x.aCompletelyDifferentField + string.Empty,
...
}The issue we have is that we can't refactor a lot of the data types because they are old and have been used since the Precambrian era, so refactoring would be extremely difficult. When there are 20-30 lines that have very similar things, seeing the extra question marks, et al, seems like it's a lot more complex than simply adding a string.
I'm providing some basic database training to some colleagues who are new to the topic. They're having difficulty understanding the difference between NULL and an empty string and I'm not doing a very good job of explaining it! Does anybody know a good way to explain it to beginners, specifically in a database context?
This says it all:
select NVL('','it is null') as value
from dual;
SQL Fiddle
2 things:
1) '' gets converted to NULL on insert. That's an Oracle VARCHAR2 thing.
2) select * from test where f=''; is trying to do select * from test where f=NULL, which isn't defined, and will return nothing because NULL doesn't like the equality operator. You have to use IS NULL or IS NOT NULL.
I'll add that the CHAR datatype behaves differently because it is padded.
Oracle treats '' and NULL the same. When inserting '', there is no conversion of '' to NULL, merely an interpretation of '' as NULL in the same way that the word NULL is interpreted as NULL or rtrim('a','a') is interpreted as NULL.
Here is a demonstration using the following table and insert:
drop table t1;
create table t1 (c1 varchar2(10));
insert into t1 (c1) values ('');
The insert above inserted a NULL value for c1. You can select that row as follows:
SELECT c1 FROM t1;
When you add a WHERE clause to compare equality and one of the values being compared is NULL, the result will always be unknown. Unknown will evaluate to false except that further operations on an unknown value produce unknown values. All of the following return no rows because the WHERE clauses contain conditions that will never be true regardless of the data.
SELECT c1 FROM t1 WHERE c1 = '';
SELECT c1 FROM t1 WHERE c1 = NULL;
SELECT c1 FROM t1 WHERE '' = '';
SELECT c1 FROM t1 WHERE NULL = NULL;
Oracle provides a special syntax to retrieve rows with a particular column having null values -- IS NULL.
SELECT c1 FROM t1 WHERE c1 IS NULL;
There are a few conditions in which oracle compares NULLS treating them as equal to other NULL values such as in DECODE statements and in compound keys.
More information can be found in the SQL Language Reference.
When declaring variables what's the best practice?
My manager asked me to change a declaration from null to an empty string and I don't really see why?
Edit: This is for JavaScript