Is it possible to find out how big the data is in KB or MB for individual columns in a table? I have a script which tells me the physical size of each table, but I would like to know how much of that is taken up by certain columns in the database, especially when I have XML stored in a column.
Any help much appreciated
Cheers
Use COL_LENGTH() to Get a Column's Length in SQL Server In SQL Server, you can use the COL_LENGTH() function to get the length of a column. More specifically, the function returns the defined length of the column, in bytes. The function accepts two arguments: the table name, and the column name.
Use the LEN to return the number of characters encoded into a given string expression, and DATALENGTH to return the size in bytes for a given string expression.
You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.
You should be able to use the datalength function, something like
select sum(datalength(yourfield))
from yourtable
This will summate the datalengths of all the entries of that field in the table - it will not account for overheads such as variable length field pointers, space in the nullability bitmap etc.
For view size of "all columns a table", you can first generate fields of your table with:
SELECT 'SUM(DATALENGTH('+Column_name+')) / (1024*1024) as '+Column_name+'_MB,'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '--TABLE_NAME--'
and next, run this query:
SELECT
/*result previous query (with remove last comma)*/
FROM --TABLE_NAME--
This will return all columns in a specific database with their data size and can easily be updated to only return the numbers for a specific table or column.
USE [YourDatabase]
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
CREATE TABLE #temp (tablename varchar(max), columnname varchar(max), sizeinkb float)
DECLARE MY_CURSOR Cursor LOCAL FAST_FORWARD
FOR SELECT table_name, column_name, table_schema FROM INFORMATION_SCHEMA.COLUMNS
Open My_Cursor
DECLARE @table varchar(max), @column varchar(max), @schema varchar(max)
Fetch NEXT FROM MY_Cursor INTO @table, @column, @schema
While (@@FETCH_STATUS <> -1)
BEGIN
DECLARE @sql varchar(1000) = 'INSERT #temp SELECT ''' + @schema + '.' + @table + ''', ''' + @column + ''', sum(isnull(datalength([' + @column + ']), 0)) / 1024.0 FROM [' + @schema + '].[' + @table + '] (NOLOCK)'
EXEC (@sql)
FETCH NEXT FROM MY_CURSOR INTO @table, @column, @schema
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
GO
SELECT *, sizeinkb / 1024.0 sizeinmb FROM #temp ORDER BY 3 DESC
Select SUM(DATALENGTH(columnsA)) / 1024.0 AS KB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With