(NOT) NULL for NVARCHAR columns - sql

Allowing NULL values on a column is normally done to allow the absense of a value to be represented. When using NVARCHAR there is aldready a possibility to have an empty string, without setting the column to NULL. In most cases I cannot see a semantical difference between an NVARCHAR with an empty string and a NULL value for such a column.
Setting the column as NOT NULL saves me from having to deal with the possibility of NULL values in the code and it feels better to not have to different representations of "no value" (NULL or an empty string).
Will I run into any other problems by setting my NVARCHAR columns to NOT NULL. Performance? Storage size? Anything I've overlooked on the usage of the values in the client code?

A NULL indicates that the value in the column is missing/inapplicable. A blank string is different because that is an actual value. A NULL technically has no data type where as a blank string, in this case, is nvarchar.
I cant see any issues with having default values rather than NULL values.
In fact, it would probably be beneficial as you wouldn't have to worry about catering for NULL values in any of your queries
e.g
Select Sum(TotalPrice) as 'TotalPrice' From myTable Where CountOfItems > 10
much easier than
Select Sum(IsNull(TotalPrice,0)) as 'TotalPrice' From myTable Where IsNull(CountOfItems,0) > 10
You should use default constraints in your DDL to ensure that no rogue NULL's appear in your data.

The concept of the NULL value is a common source of confusion. NULL is not the same as an empty string, or a value of zero.
Conceptually, NULL means "a missing unknown value" and it is treated somewhat differently from other values. For example, to test for NULL, you cannot use the arithmetic comparison operators such as =, <, or <>.
If you have columns that may contain "a missing unknown value", you have to set them to accept NULLs. On the other hand, an empty string simply means that the value is known, but is empty.
For example: If a "Middle Name" field in a "Users" table is set to NULL, it should mean that the middle name of that user is not known. The user might or might not have a middle name. However, if the "Middle Name" field is set to an empty string, this should mean that the user is known to have no middle name.

If anything I'd say that it'll be easier to use the table if you don't allow NULLs, since you won't have to check for NULLs everywhere in code, so I'd only set a column to allow NULLs if I need to handle unknown rather than empty values.

What ho1 said. But you'd be ill-advised to define a column NOT NULL and then have a special value for 'Unknown'.

Related

Why does an int column values defaults to '0' when passed empty?

I have table with an integer column.
CREATE TABLE [dbo].[tble1](
[id] [int] NOT NULL,
[test] [nchar](10) NULL
)
When I try to insert some values and pass an empty string to the id column like below, it gets inserted and the value of the id column is 0 by default.
INSERT INTO [dbo].[tble1]
([id],[test])
VALUES
('','a')
I couldn't find any satisfying reasoning behind it. Could some one please share your thoughts on this?
What is happening is that '' is being converted to an integer. The rules are that a string can be converted, based on the digit characters in the string.
If a string is empty, it gets converted to 0.
So, the conversion is happening at the very "top" level. The types don't match so SQL Server attempts an implicit conversion.
Unfortunately, the documentation is not really clear on the topic:
Character expressions that are being converted to an exact numeric
data type must consist of digits, a decimal point, and an optional
plus (+) or minus (-). Leading blanks are ignored. Comma separators,
such as the thousands separator in 123,456.00, are not allowed in the
string.
To be honest, I would interpret the "must consist of digits" as saying that there must be at least one digit (although technically in English "zero" is treated as a plural, I don't necessarily think of plurals as including zero elements). However, the empty string has been used -- pretty much for forever -- as a valid value for any type across a broad range of databases.
It will try to Convert ' ' to Integer and it got succeeded.
SELECT CONVERT(INT, '')
Output
0
You are getting defaulted value to 0, as you have NOT null, defined for the column,
if you keep ID as null, then it will put NULL,
Also, if you want to populate the value automatically then you set the identity for the column

Oracle:Difference between NULL and EMPTY string

I am in a situation where my query is not returning any values due to oracle behaviour.
Problem is this:Oracle considers EMPTY STRING as NULL when INSERTING DATA but not when SELECTING BACK the data.
This is not a duplicate of Why does Oracle 9i treat an empty string as NULL? because here i am not asking for the reason to this problem,i am well aware of the reason,i am asking for a solution to this problem.
This is my table structure
CREATE TABLE TEST
(
ID NUMBER not null,
NAME VARCHAR2(255)
)
when inserting the values oracle will accept
INSERT INTO TEST values(1,'');
I found out that internally oracle converts Strings of Zero length to NULL and stores
But my query
SELECT * FROM TEST
WHERE NAME = INPUT;(INPUT='')
(Input is passed from front end and will sometimes have empty string)
will not return any result
I can not write dynamic query due to performance issue
Somebody who faced this issue before please let me know how do i compare EMPTY STRING with NULL
The problem is that Oracle (by default) treats empty strings as NULL. Hence:
where name = ''
is the same as:
where name = NULL
and both always fail (because they return NULL).
You can fix this in various ways. One method is:
where (name = INPUT or name is null and INPUT is null)
Or, if you know there is an invalid name:
where coalesce(name, '<invalid>') = coalesce(INPUT, '<invalid>')
This is one of the most annoying features of Oracle - not found in other DB products. You will have to put up with it, for all the other massive advantages of Oracle - and be prepared that the learning curve is not very quick.
To check for equality of nulls, the best approach is to write explicitly what you are doing, instead of using gimmicks. For example:
... where NAME = INPUT or (NAME IS NULL and INPUT IS NULL)
This will make it a lot easier for yourself, and for others after you, to debug, maintain, and modify the code, now and especially later. There are other solutions, too, but they may confuse others in the future; for example, this is something I wouldn't use (for several reasons):
... where NAME || 'z' = INPUT || 'z'
although it would obviously achieve the same result with less typing.
One more thing, in most cases you should NOT include in your results rows where you treat NULL as "equal" - the values are NULL for a reason, and in most cases if you make two NULL's equal, that is NOT the intended result.

PL/SQL Oracle condition equals

I think I'm encountering a fairly simple problem in PL/SQL on an Oracle Database(10g) and I'm hoping one of you guys can help me out.
I'm trying to explain this as clear as possible, but it's hard for me.
When I try to compare varchar2 values of 2 different tables to check if I need to create a new record or I can re-use the ID of the existing one, the DB (or I) compares these values in a wrong way. All is fine when both the field contain a value, this results in 'a' = 'a' which it understands. But when both fields are NULL (or '' which Oracle will turn into NULL) it can not compare the fields.
I found a 'solution' to this problem but I'm certain there is a better way.
rowTable1 ROWTABLE1%ROWTYPE;
iReUsableID INT;
SELECT * INTO rowTable1
FROM TABLE1
WHERE TABLE1ID = 'someID';
SELECT TABLE2ID INTO iReUsableID
FROM TABLE2
WHERE NVL(SOMEFIELDNAME,' ') = NVL(rowTable1.SOMEFIELDNAME,' ');
So NVL changes the null value to ' ' after which it will compare in the right way.
Thanks in advance,
Dennis
You can use LNNVL function (http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions078.htm) and reverse the condition:
SELECT TABLE2ID INTO iReUsableID
FROM TABLE2
WHERE LNNVL(SOMEFIELDNAME != rowTable1.SOMEFIELDNAME);
Your method is fine, unless one of the values could be a space. The "standard" way of doing the comparison is to explicitly compare to NULL:
WHERE col1 = col2 or col1 is null and col2 is null
In Oracle, comparisons on strings are encumbered by the fact that Oracle treats the empty string as NULL. This is a peculiarity of Oracle and not a problem in other databases.
In Oracle (or any RDBMS I believe), one NULL is not equal to another NULL. Therefore, you need to use the workaround that you have stated if you want to force 2 NULL values to be considered the same. Additionally, you might want to default NULL values to '' (empty) rather than ' ' (space).
From Wikipedia (originally the ISO spec, but I couldn't access it):
Since Null is not a member of any data domain, it is not considered a "value", but rather a marker (or placeholder) indicating the absence of value. Because of this, comparisons with Null can never result in either True or False, but always in a third logical result, Unknown.
As mentioned by Jan Spurny, you can use LNNVL for comparison. However, it would be wrong to say that a comparison is actually being made when both values being compared are NULL.
This is indeed a simple and usable way to compare nulls.
You cannot compare NULLS directly since NULL is not equal NULL.
You must provide your own logic who you would like to compare, what you've done with NVL().
Take in mind, you are treating NULLS as space, so ' ' in one table would be equal to NULL in another table in your case.
There are some other ways (e.g. LNNVL ) but they are not some kind of a "better" way, I think.

What is NULL in SQL?

I am confuse about what is the value of NULL in SQL. NULL I think is empty.
So will it contain any garbage value or unknown value or like 0 in integer or blank in character?
In simple worlds you can say that Null is not a data value, but a marker for an unknown value.
So any mathematical operations performed on NULL will result in NULL. For example,
10 + NULL = NULL
Similarly if you do string concatenation with string you get:-
'String ' || NULL || 'Concatenation' -- Result is NULL
So you can say that Null means either "not applicable" or "don't know": it is not the same as zero (0) or any other default value, but more importantly, null is treated quite differently from other values in SQL, because it literally has no value.
An example to explain what it means when we say that NULL means UNKNOWN VALUE:
StudentName TestResult
X 78
A 89
B 67
C NULL
So you can see that the student C got NULL marks in the test. So what
does that mean?
Now one can say that the student does not sit in the test or it may be that the student's data is not avaialable. But it definitely does not mean that the student got 0(as if you assign 0 to the student then it would mean that the student appeared in the test and got zero) marks in the test. All we can say that the data for the student is UNKNOWN or NULL
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces.
If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
Read more about this here.
NULL is a keyword used to represent unknown/missing data.
Say you have an optional column in your table. You can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.
Check this for more details.
It is to indicate that a data value does not exist in the database.NULL is also an SQL reserved keyword used to identify the Null special marker.
NULL means “a missing unknown value” and it is treated somewhat differently from other values.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces.
10 * NULL -- Result is NULL
Null (SQL)
SQL NULL
Working with NULL Values
Null is not empty actually but it is considered as uknown value, from dumentation
Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values.
You can ready more here

Can I insert an empty string in a NOT NULL field?

Can I insert an empty string in a not null field?
insert into xyz(A,B) values(1,''); // is this possible if B is NOT NULL?
Depends on DBMS.
Oracle no: '' and null are identical
SQL-Server yes: '' and null are different values.
Yes you can... The concept of the NULL value is a common source of confusion for newcomers to SQL, who often think that NULL is the same as an empty string '', or a value of zero.
This is not the case. Conceptually, NULL means "a missing unknown value" and it is treated somewhat differently from other values. For example, to test for NULL, you cannot use the arithmetic comparison operators such as =, <, or <> in most DBMSes.
As Daniel said, yes you can insert the zero-length string into a NOT NULL field (except on Oracle). However, if you want to rule out zero-length strings as well, you can add a constraint:
ALTER TABLE xyz ADD CONSTRAINT CHECK (b LIKE '_%');
Most modern databases have a regular-expression operator or function you could use for constraints as well, but the exact syntax varies from database to database.