SQL Text vs VARCHAR
When to use VARCHAR and When to use TEXT
TEXT
is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.VARCHAR
is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x)
, where x > 8000, you get an error:Server: Msg 131, Level 15, State 3, Line 1These length limitations do not concern
The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)
VARCHAR(MAX)
in SQL Server 2005, which may be stored out of row, just like TEXT
.Note that
MAX
is not a kind of constant here, VARCHAR
and VARCHAR(MAX)
are very different types, the latter being very close to TEXT
.In prior versions of SQL Server you could not access the
TEXT
directly, you only could get a TEXTPTR
and use it in READTEXT
and WRITETEXT
functions.In SQL Server 2005 you can directly access
TEXT
columns (though you still need an explicit cast to VARCHAR
to assign a value for them).TEXT
is good:- If you need to store large texts in your database
- If you do not search on the value of the column
- If you select this column rarely and do not join on it.
VARCHAR
is good:- If you store little strings
- If you search on the string value
- If you always select it or use it in joins.
By searching here I mean issuing any queries whose result depends on the value of the
TEXT
or VARCHAR
column. This includes using it in any JOIN
or WHERE
condition.As the
TEXT
is stored out of row, the queries not involving the TEXT
column are usually faster.Some examples of what
TEXT
is good for:- Blog comments
- Wiki pages
- Code source
VARCHAR
is good for:- Usernames
- Page titles
- Filenames
TEXT
.Otherwise use
VARCHAR
.
Comments
Post a Comment