Nulls in T-SQL.

Status
Not open for further replies.

indigo

Well-known member
5,606
My "mentor" tells me "Nulls are tricky".

I disagree. Nulls follow a different set of rules, but these rules are not unknowable, they're not even that hard.

So instead of using Nulls on a column that allows Nulls, a co-worker is using 1/1/9999 on this datetime field. This makes absolutely no sense to me.

I'm pissed. I write a program to modify 3 of the date attributes, Effective, Expiration, and Filing, and now other programs have problems because they rely on "Null" being 1/1/9999.

Well nobody fucking told me this! What sense does that make anyways?!? If you didn't want Nulls, why is it a Nullable field!?! It should be Not Null, Default 1/1/9999!

The two coders I'm working with (we're also in charge of building the db), use the db like it were a big messy text file. numeric/decimal when the field should be tinyint, varchar/nvarchar intermixed with no discernable pattern, DateCreated[datetime] instead of Timestamp, Sorting_Sequence[numeric] when that's really program specific, only a 0 or 1, and should be *in the program*.

It's a huge mess.

I'm so incredibly fustrated. I'm thinking I need to take control of the db, but it's not like I'm a pro or anything... it just seems the other two (who are far more experienced than myself) just don't have the dicipline (will?) to do it as I see fit... Again, I could be way wrong on my views, but these seem so glaringly obvious to me...

comments?
 

walkern

Smack-Fu Master, in training
53
Granted, it sounds like they didn't set up the db properly, but I think you certainly are discounting the trickiness of NULLs. Having been involved in some database projects where NULLs give some tricky errors due to NULL propagation, I can understand where those guys are coming from. (NULL progation is where any operation involving the NULL basically returns either NULL or ignores those entries. IE 4 + NULL = NULL. NULL is "Blah" = NULL. Count() on {1, 2, NULL} is 2. Basically, you end up having to special case NULL in every operation, and use builtin functions like Nz() or IsNull()) I probably wouldn't use NULLs in my own setup.

However, you should certainly make sure that the db is stringently enforcing its specifications. The date fields should be marked Not Null, make sure you don't allow NULL foreign keys, etc.
 

indigo

Well-known member
5,606
I appreciate that Nulls are different, but I wouldn't do a count on a Nullable field for example. I'm using vbscript right now, transitioning to C#, and I move Nulls to "" in code. I haven't found where this falls through. Maybe you could point it out to me though:

code:<HR>
Code:
If trim(rsTemp("IntField") & " ") = "" Then
  Response.Write("The Value is Null")
End If

Stored Procedures are another thing, but (bad I know), were not making alot of use of them right now.

Also, I'm trying to get rid of Nulls. You'd cry if you saw the db... you really would. It's amazing anything works. I'll be so happy when I'm on the new project/system, where I'll have some input on foundation... While I'm learning C#, VB.NET is probably going to be the main language. *Maybe* JScript.NET... but it's going to be XML at the heart (for technical reasons related to International Documents Standards for Cargo Haulers, not just for the spiffy buzz-wordiness ;) ), with all the spiffy bells and whistles...

Sorry, I just needed to vent... after the next project were going to re-write the entire system I complained about above, so that should keep me busy for awhile... ;)
 

temp

Seniorius Lurkius
44
Indgo, Your code
code:<HR>
Code:
If trim(rsTemp("IntField") & " ") = "" Then  
    Response.Write("The Value is Null")
End If
has some problems.

If you are really testing for Null you should write
code:<HR>
Code:
 If IsNull(rsTemp("IntField").value) Then
    Response.Write("The Value is Null")
End If
Concatenating a Null with an empty string is a useful vbscript trick when the distinction bewteen a null, empty and the empty string isn't important, but it's not good when you are testing for Nulls.

But I agree that Nulls can improve database design a lot. There are times when a magic value à la "1999-01-01" initially seems like a good idea, but in my experience it usually turns out that careful use of nullable fields together with the T-SQL function ISNULL() makes for a more transparent and maintainable design.
 

temp

Seniorius Lurkius
44
Like you said your method will work most of the time -- no argument there. However, the IsNull vbscript function gets you two advantages:

1) It's easier to read. It's pretty obvious to another coder that the IsNull() function tests for a null. The syntax where you first concatenate with a space, then trim whitespace and finally compare to an empty string takes a bit longer to read.

2) It's more accurate. Your way doesn't really distinguish between the cases where the database field contains a Null, an empty string and a series of spaces. Usually it makes no difference and sometimes that's exactly what you want to accomplish. But if you stick with the IsNull() variant as your default choice there will never be any doubt on whether you are testing for Null, or checking to see if the database field has any regular stuff inside.

Mostly it's not that important, but I'm paranoid from countless hours wasted chasing bugs due to faintly ambiguous vbscript statements ;)
 

technophile

Ars Legatus Legionis
23,768
Originally posted by indigo:
In most cases I can think of... the trim() works suitably, but if there's a "better" way, I'm all for doing it the right way instead.
If you don't want to use IsNull you can still avoid the trim function call.

code:<HR>
Code:
If rsTemp("IntField") & "" = "" Then
      Response.Write("The Value is Null")
End If
Note that there's no space in the string you're concatenating, it's just the empty string.

Also, VB occasionally has issues with IsNull not returning true when the variable is Nothing or Empty instead. :rolleyes: The number of times I've wished VB had an "HasAnythingInIt" function that would test for Nothing, Empty, and Null, and return True if any of them are true... So instead of using IsNull, I'd use HasAnythingInIt, and define HasAnythingInIt as:
code:<HR>
Code:
Public Function HasAnythingInIt(var As Variant) As Boolean
    IsAnythingInIt = IsEmpty(var) Or IsNull(var) Or (var Is Nothing)
End Function

That said, I have never encountered a real life situation where I needed to treat "" different from NULL (and I would consider needing to fairly brain-damaged), so I usually just use the & "" = "" trick.
 

HL7

Ars Praefectus
3,523
Subscriptor++
Originally posted by indigo:
I disagree. Nulls follow a different set of rules, but these rules are not unknowable, they're not even that hard.
True. But they're also counterintuitive and inconsistent with other rules. Equality tests will return NULL when one term is null, for instance, and you must remember to compare ISNULL values if you want to know if one field contains data and the other is null.

Nulls _are_ tricky, even when you're accustomed to them.

So instead of using Nulls on a column that allows Nulls, a co-worker is using 1/1/9999 on this datetime field. This makes absolutely no sense to me.
I agree that this is a terrible practice, even if the column isn't nullable. It's asking for trouble later when this DB is maintained. I'll bet that none of this is documented.

Someone will inevitably want changes made to the database years down the road. When that happens, it will probably be easier and cheaper to build a new one than modify the existing one.

"Magic" values should never be used unless they're (1) absolutely necessary, and (2) well-documented. For instance, when I need a discriminator for a subtype cluster, the only choice is to use some sort of "magic" value. But I usually choose a char field so that it's more obvious what each choice means. For instance, in an employee health database where everything is a subtype of "EHRecord," I've used a char(2) field where "TB" means TB tests, "IM" means immunizations, and "TI" means titers.

I appreciate that Nulls are different, but I wouldn't do a count on a Nullable field for example.
Sure you would. That's the whole point of making the field nullable. When you do an aggregate function on a nullable field, the nulls don't get counted, which is great since null basically means "I don't know." It allows you to analyze the data you actually have, and throw out records with no value in the field, rather than skewing the results with a bunch of zeroes.

Originally posted by technophile:
Also, VB occasionally has issues with IsNull not returning true when the variable is Nothing or Empty instead.
True ... but they are different, so this is correct behavior. Nothing can only be assigned to an Object, and it's like a null pointer in C. Empty means that there is a value, and it's empty, while Null means there is no value.

That said, I have never encountered a real life situation where I needed to treat "" different from NULL (and I would consider needing to fairly brain-damaged)
It wouldn't be brain-damaged. Null means "I didn't enter a value, or I don't know the value." ZLS means "I know the value, and the value is nothing." They're completely different, and a situation where you'd need to treat them differently isn't inconceivable.

BTW, your function should be named "HasNothingInIt" ;)
 

TheJet

Ars Praefectus
4,598
Subscriptor++
Does the above HasAnythingInIt actually work?? In VBScript this type of code will cause a gigantic error when trying to compare a non-object variable with Nothing (i.e. Empty != Nothing). It's because of this (and not having short-circuited boolean logic) that you have to do:

code:<HR>
Code:
If IsObject(var) Then If var Is Nothing Then HasAnythingInIt = False

Otherwise, I'm constantly getting the "Variable is not an object error". Basically I got into the habit (when doing stuff in ASP that required objects) of the following:

code:<HR>
Code:
If Not IsObject(var) Then Set var = Nothing
If var Is Nothing Then
  '//... do object construction logic
End If

Anyway, referencing the initial post, Timestamps should in general not be used as "Creation Dates", since usually you really want a creation date to be an actual date, not a unique binary number, from the T-SQL documentation:

The Transact-SQL timestamp data type is not the same as the timestamp data type defined in the SQL-92 standard. The SQL-92 timestamp data type is equivalent to the Transact-SQL datetime data type.

We regularly use it to avoid "last-in-wins" type update scenarios to provide lock-free record "locking". However, it's no good as an actual date value.

TheJet

P.S. On the NULL thing, I regularly use NULLs everywhere, they are extremely useful when you really want to know that the column wasn't filled in. We've tried "magic" values and as was stated above, they become an absolute nightmare, especially when importing/exporting data across systems. They do make coding a small bit harder, but at least the coding is consistent and the "magic" value is hard-coded everywhere. You learn to love the ISNULL() SQL function. The other benefit is that it allows you at least a little in-line IF/THEN functionality (i.e. SELECT ISNULL(SalePrice, RegularPrice) AS ItemPrice FROM ...)
 

indigo

Well-known member
5,606
I don't follow about your TimeStamp comments.

I probably didn't make it clear as I haven't read this thread in awhile, but most of the tables I'm working on require History be kept.

ie: You create a new document in the system. You want to modify Term 6 of the document. This creates a new document revision so that the old document can always be retrieved and succesive updates to the document do not affect the old document. IOW these records are Inserted, not Updated, and never Deleted. If you make a typo in the document, that typo is there forever. You have to edit the affected text to correct the typo, which in turn creates a new record for that Term.

This is true of the Lines tables anyways. The Header tables are indeed Updated, so thanks for informing me of the difference, lest I destroy CreateDate data... ;)

nm... I guess I got you after all... sorta...
 

TheJet

Ars Praefectus
4,598
Subscriptor++
indigo:

Just because it's the same size means very little. The timestamp field in SQLServer is not updateable and has no bearing on a date or time. It is very much like a GUID is in windows, it means absolutely nothing, it's just guaranteed to be unique within a given database (but not within a given server). Although GUIDs are only guaranteed from a statistical basis (i.e. it's just not very likely to generate the same one as any that have been previously generated).

If you want to know when (i.e. a date and time) the actual document was created, you can just setup a non-null field called CreateDate and have it filled with a default of GETDATE(). This will dump the current date/time into that field on INSERT. Then it's up to the program to ensure that it never updates that column (although you could probably setup a trigger to enforce this).

TheJet

EDIT:

The point is that you cannot read an actual date/time from a timestamp column -- a timestamp is simply a unique value that will allow you to sort things by last update time

HL7, I don't know if this is explicitly true. It may be true in a large subset of cases, but in general I think this is false, much like sorting by an identity field doesn't always return a list sorted by insert order. Once the system runs out of unique values, it will start recycling unused ones. Plus, while it looks like the algorithm MS uses is (new timestamp = last timestamp +1) I don't know that this is the exact algorithm used, without knowing the exact algorithm, it's unwise to use it for anything other than the unique identifier it was intended to be.
 

HL7

Ars Praefectus
3,523
Subscriptor++
Originally posted by TheJet:
HL7, I don't know if this is explicitly true. It may be true in a large subset of cases, but in general I think this is false, much like sorting by an identity field doesn't always return a list sorted by insert order. Once the system runs out of unique values, it will start recycling unused ones.
I don't know if it will or not. The SQL Server glossary says:

timestamp data type
A SQL Server system data type that is a monotomically increasing counter whose values are always unique within a database. A timestamp is the date and time the data was last modified.
I always assumed that a timestamp could tell you relative time in terms of "before" and "after", but not actual time or time intervals.

OK, I just looked it up ... according to this MS KB article,

Timestamps increase until the maximum value that can be stored in 6 bytes (2**48) is reached. When this maximum is reached, the database will not permit any more updates.
This seems kind of silly. But as they say, "This is not a major concern because at 100 transactions per second, 2**48 will not wrap for more than 100 years."
 

TheJet

Ars Praefectus
4,598
Subscriptor++
HL7,
Well that's rather interesting, I wonder if the same information applies to SQL 2000 (since it wasn't listed in the "applies to" section), I'm trolling through the SQL 2000 documentation which is where I pulled the first quote. It seems rather silly that they would just refuse updates when the timestamp reaches the top limit of the number space. Especially since the number increases with absolutely _every_ database update (where timestamps are found on rows). We've designed quite a few applications where you could potentially update 100 table rows in a single update, as the system scales up you could easily be processing 1000 updates/sec, which would run you out of search space in less than 5 years...

This seems like a major problem, especially for large systems... I'll have to keep that in mind in the future :(.

TheJet

EDIT:

OK, I found this little gem in the SQL 2000 docs ;)

Microsoft® SQL Server™ 2000 includes four types of special data:

timestamp
Is used to indicate the sequence of SQL Server activity on a row, represented as an increasing number in a binary format. As a row is modified in a table, the timestamp is updated with the current database timestamp value obtained from the @@DBTS function. timestamp data is not related to the date and time of an insert or change to data. To automatically record times that data modifications take place in a table, use either a datetime or smalldatetime data type to record the events and triggers.

Note In SQL Server, rowversion is a synonym for timestamp.

AND

timestamp
The SQL Server timestamp data type has nothing to do with times or dates. SQL Server timestamps are binary numbers that indicate the relative sequence in which data modifications took place in a database. The timestamp data type was originally implemented to support the SQL Server recovery algorithms. Each time a page was modified, it was stamped with the current @@DBTS value and @@DBTS was incremented by one. This was sufficient for recovery to determine the relative sequence in which pages had been modified, but the timestamp values had no relationship to time.

In SQL Server version 7.0 and SQL Server 2000, @@DBTS is only incremented for use in timestamp columns. If a table contains a timestamp column, every time a row is modified by an INSERT, UPDATE, or DELETE statement, the timestamp value in the row is set to the current @@DBTS value, and then @@DBTS is incremented by one.

Never use timestamp columns in keys, especially primary keys, because the timestamp value changes every time the row is modified.

To record the times data modifications take place in a table, use either a datetime or smalldatetime data type to record the events and triggers to automatically update the values when any modification takes place.

Now I'm really curious, since this seems to imply that they have changed the behavior of this column in SQL 2000, although it also seems to point to a conflict between the KB article you posted above and the documentation...
 

indigo

Well-known member
5,606
Server Books Online for SQL2K specifically states Timestamp is binary(8).

So that information doesn't seem to necessarily apply...

I'm confused about the worth of Timestamp now since every table I can think of that I have makes use of an identity field...

Still, it's much nicer to be corrected before I do something stupid than to have to fix a problem after I did said stupid thing... ;)

I think I'll just avoid TimeStamp from now on then... I don't see a practical advantage over "DateCreated" DateTime, or Identity Int fields... It combines both into one it seems... sort of... but with constraints I'm not really clear on, and besides, those two things are necessarily exclusive fields in practice for me atleast.
 

technophile

Ars Legatus Legionis
23,768
Originally posted by TheJet:
Does the above HasAnythingInIt actually work?? In VBScript this type of code will cause a gigantic error when trying to compare a non-object variable with Nothing (i.e. Empty != Nothing). It's because of this (and not having short-circuited boolean logic) that you have to do:
Caught me. :) No, it doesn't actually work because of VB not short-circuiting (which pisses me off every time I write an If...Then). In reality you'd have to write something like

code:<HR>
Code:
Public Function HasAnythingInIt(var As Variant) As Boolean
    HasAnythingInIt = True
    If IsEmpty(var) Then
        HasAnythingInIt = False
    ElseIf IsNull(var) Then
        HasAnythingInIt = False
    ElseIf var Is Nothing Then
        HasAnythingInIt = False
    End If
End Function

Technically you should also insert an error handler to catch unforeseen problems etc.

Of course for specific applications you could check for "not initialized" values (for instance, -1 for an integer whose domain is numbers greater than or equal to zero, or an empty string, etc).
 
Status
Not open for further replies.