Taking advantage of the cue, DATALENGTH
has a variety of behaviors, depending on the type of data you use, eg:
DECLARE @exemploChar char(30)
SET @exemploChar = 'stack'
SELECT DATALENGTH(@exemploChar)
In the above example, the column, represented by the variable @exemploChar
, will receive the total size determined in the column, because the data type char
has a fixed size, that is, it will occupy 30 bytes (1 byte per character) , even if the contents of the column, occupy, as in our example, only 5 characters.
DECLARE @exemploVarchar varchar(30)
SET @exemploVarchar = 'stack'
SELECT DATALENGTH(@exemploVarchar)
In the example above, we created the column, exemplified by the variable @exemploVarchar
, with data type varchar
. Because it is a variable data type, the size used was only 5 bytes (5 characters), not the 30 (1 byte per character) predetermined at creation.
Out of curiosity, I'll make two more examples, but using unicode.
DECLARE @exemploNchar nchar(30)
SET @exemploNchar = 'stack'
SELECT DATALENGTH(@exemploNchar)
For this, we can notice that the size of the column has doubled to 60 bytes consumed. This happens because the unicode data type consumes two bytes per character and not one.
DECLARE @exemploNvarchar nvarchar(30)
SET @exemploNvarchar = 'stack'
SELECT DATALENGTH(@exemploNvarchar)
Finally, in this example the consumption will be 10 bytes (2 bytes per character).
If you're wondering when to use one or the other:
-
char
is good for writing, since the size of the column is already determined, and there is no need for extra processing for this task.
-
varchar
is good for reading, because in 90% of cases, the column size will be smaller than the default size
-
unicode
is good to use when importing data from another database or need to handle special characters in our language. In this case, unicode does not attempt to convert, keeping the original data, in addition to gaining speed.
It is worth remembering that if you want to see the properties of a table and see the size determined for each column, you can use the commands below:
Select the object and with the keyboard, press ALT + F1