Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the CHAR datatype in SQL obsolete? When do you use it?

Tags:

types

sql

char

The title pretty much frames the question. I have not used CHAR in years. Right now, I am reverse-engineering a database that has CHAR all over it, for primary keys, codes, etc. How about a CHAR(30) column?

Edit: So the general opinion seems to be that CHAR if perfectly fine for certain things. I, however, think that you can design a database schema that does not have a need for "these certain things", thus not requiring fixed-length strings. With the bit, uniqueidentifier, varchar, and text types, it seems that in a well-normalized schema you get a certain elegance that you don't get when you use encoded string values. Thinking in fixed lenghts, no offense meant, seems to be a relic of the mainframe days (I learned RPG II once myself). I believe it is obsolete, and I did not hear a convincing argument from you claiming otherwise.

like image 853
cdonner Avatar asked Apr 17 '09 01:04

cdonner


People also ask

Can we use CHAR data type in SQL?

CHAR Datatype:It is a datatype in SQL which is used to store character string of fixed length specified. If the length of the string is less than set or fixed-length then it is padded with extra blank spaces so that its length became equal to the set length when PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled.

Why would you use CHAR instead of VARCHAR?

Varchar take 1 byte for each character along with some extra bytes to store length information. We can use char datatype when we know the length of the string. We can use it when we are not sure of the length of the string. Char datatype can be used when we expect the data values in a column to be of same length.

When should you use VARCHAR as a datatype?

CHAR, VARCHAR, and VARCHAR(MAX) CHAR columns should be used for columns that vary little in length. String values that vary significantly in length and are no longer than 8,000 bytes should be stored in a VARCHAR column. If you have huge strings (over 8,000 bytes), then VARCHAR(MAX) should be used.

What is the advantage of using VARCHAR data type over CHAR data type in SQL?

it can require less storage than fixed-length types because it uses only as much space as it needs. varchar also uses 1 or 2 extra bytes to record the value's length. for example varchar(10) will use up to 11 bytes of storage space. varchar helps performance because it saves space.


1 Answers

I use char(n) for codes, varchar(m) for descriptions. Char(n) seems to result in better performance because data doesn't need to move around when the size of contents change.

like image 162
Otávio Décio Avatar answered Sep 24 '22 12:09

Otávio Décio