Friday 21 September 2012

What's the difference between CHAR and VARCHAR data types and when do I use them?

CHAR and VARCHAR data types are both non-Unicode character data types with a maximum length of 8,000 characters. 

The main difference between these 2 data types is that a CHAR data type is fixed-length while a VARCHAR is variable-length.  If the number of characters entered in a CHAR data type column is less than the declared column length, spaces are appended to it to fill up the whole length.

Another difference is in the storage size wherein the storage size for CHAR is n bytes while for VARCHAR is the actual length in bytes of the data entered (and not n bytes).

CHAR is faster than VARCHAR when used in joins and queries. 

when do I use them?
You should use CHAR data type when the data values in a column are expected to be consistently close to the same size.  example SSN, SystemIDs, EMPIDs,etc..

On the other hand, you should use VARCHAR when the data values in a column are expected to vary considerably in size.

The above explanation is also applicable to NCHAR and NVARCHAR datatypes.

No comments:

Post a Comment