Friday, November 22, 2013

Difference between char, varchar, nchar and nvarchar data type in SQL Server database

What is difference between char and varchar in SQL, followed by nchar and nvarchar, is one of the popular SQL interview question, and surprisingly not every programmer knows this basic difference. If you go with name, which you should, than you can figure out that char is a fixed length data type while varchar should be variable length data type. Though all char, varchar, nchar, and nvarchar are used to store text or String data there are subtle differences between them. As I said char is fixed length, which means a variable or a column e.g. Zipcode char(10) will take only 10 bytes to store data, including space. On the other hand a varchar variable or column will take variable space, depending upon data you store + 2 additional bytes for storing length. For example a varchar column name varchar name(20) will take 6 bytes if you store "Jack" (4 + 2) and 7 bytes if you store "Jones" (5 + 2). In order to get better performance, you should use char for fixed length columns e.g. zipcode, where every row are under certain length e.g. 6 for India, and 5 + 4 digits postal codes for USA. On the other hand, for a variable length column it's better to use varchar data type to save the space, which is lost in case of char type, if actual data is always way less than capacity. In particular this question is next in series of couple of popular SQL interview question, e.g. difference between WHERE and HAVING clause and writing SQL query to join three tables. If you come across any other interesting SQL queries than you can also share with us, if you don't know answer, we will try to find out together.
Read more �

No comments:

Post a Comment