Using varchar(MAX) vs TEXT on SQL Server
I just read that the VARCHAR(MAX)
datatype (which can store close to 2GB of char data) is the recommended replacement for the TEXT
datatype in SQL Server 2005 and Next SQL SERVER versions.
If I want to search inside a column for any string, which operation is quicker?
-
Using a the
LIKE
clause against aVARCHAR(MAX)
column?WHERE COL1 LIKE '%search string%'
-
Using the
TEXT
column and put a Full Text Index/Catalog on this column, and then search using theCONTAINS
clause?WHERE CONTAINS (Col1, 'MyToken')
The VARCHAR(MAX)
type is a replacement for TEXT
. The basic difference is that a TEXT
type will always store the data in a blob whereas the VARCHAR(MAX)
type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.
Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX)
gives you is that it is also can be used with =
and GROUP BY
as any other VARCHAR
column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.
In regard to if you should use LIKE
to search, or if you should use Full Text Indexing and CONTAINS
. This question is the same regardless of VARCHAR(MAX)
or TEXT
.
If you are searching large amounts of text and performance is key then you should use a Full Text Index.
LIKE
is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.
For large text, the full text index is much faster. But you can full text index varchar(max)
as well.
You can't search a text field without converting it from text to varchar.
DECLARE @table TABLE (a text)
INSERT INTO @table VALUES ('a')
INSERT INTO @table VALUES ('a')
INSERT INTO @table VALUES ('b')
INSERT INTO @table VALUES ('c')
INSERT INTO @table VALUES ('d')
SELECT *
FROM @table
WHERE a = 'a'
This will give you the error:
The data types
text
andvarchar
are incompatible in the equal to operator.
Whereas this does not:
DECLARE @table TABLE (a varchar(max))
Interestingly, LIKE
still works, i.e.
WHERE a LIKE '%a%'