This is another article in the series of SQL SERVER 2016 Journey . I am pretty much sure you might aware of Gzip Compression algorithm. If not then try this link.
So, SQL SERVER 2016 introduce this two awesome functions for Compress & Decompress the data.
Before SQL SERVER 2016 version we have data compression feature like Page & Row compression (check Previous post for it Link )which is different then this column value compression.
In SQL SERVER 2016 Compress function, data compression is done via GZIP algorithm and return VARBINARY(MAX).
Below is the simple syntax of Compress function
Compress (Expression)
Here Expression can be nvarchar(n), nvarchar(max), varchar(n), varchar(max), varbinary(n), varbinary(max), char(n), nchar(n), or binary(n)
Decompress function is just opposite of compress function. It is used to decompress the value of VARBINARY which is converted using Compress function. The only tweak is you need to cast the output of Decompress function in specific data type to make it readable (if using varchar ,nvarchar compression) .
below is the simple syntax of Decompress
Decompress (Compressed string)
Let’s understand this via an example as shown below .
In this example I have taken 3 tables with exact same schema & data
- IndiandotnetFriends
- IndiandotnetFriends_Compress
- IndiandotneFriends_Decompress
You can see snap in which we are inserting same data.
As the name suggested in first table normal data from Adventureworks’s person table.
In second table we are inserting compressed value of first Name and in 3rd table we are inserting decompress value of First Name from the Compressed table.
Now, let’s check compress & decompress table data
Now, Your might thinking that the output of both compress and decompress is not readable.
So you are right to make data readable of Decompress table we need to type cast.
See below snap for same.
Till now we know how to use this Compress & Decompress function. Now, let me share the benefit of using Compress. if you see below snap you will find that data length of compress is comparatively less than normal and decompressed data length .
Obviously, compression helps you somewhere in the overall performance of your application.
The good point is you can pass the compress data to your .net application and decompress using GzipStream as well.
The only thing which we need to take care is type casting. Suppose your base column which compressed is VARCHAR then you need to typecast again in VARCHAR.
Now, next question is where we can use this functions. So, we can use in compressing large object like binary data in which we save jpg, pdf , word document etc..
I hope you will be excited in using this function.
Please, share your input.
RJ!