Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find length of varchar(max) column

I am trying to find the length of string columns specified in a table.

I do this with the help of CHARACTER_MAXIMUM_LENGTH from infomation_schema.columns.

However, for varchar(max) it returns -1. I was wondering if I should return the maximum allowed length whenever varchar(max), nvarchar(max), etc columns are present in the table?

like image 428
kanu Avatar asked Dec 30 '25 17:12

kanu


1 Answers

Yes, the maximum length of a varchar(max) or nvarchar(max) column is not unlimited. The storage limit is 2GB (2^31 -1 bytes). It behaves as a regular varchar/nvarchar column when the data is less than 8kb. Then when the data for a individual row is greater than 8kb, it is stored as a large-object text/ntext value. You can think of it like a wrapper for the 2 data types.

However, the maximum character length is not 2000000000. It is 2147483645 for a varchar(max) column and 1073741822 for a nvarchar(max) column. This is because an nvarchar has 2 bytes per character and a varchar has 1 byte per character and 2 bytes are needed to store the data length of a variable column.

I don't think any extra metadata is subtracted from the 2GB limit but I will comment tomorrow if I find anything else.

like image 159
Russell Hart Avatar answered Jan 02 '26 10:01

Russell Hart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!