Skip to main content

How to check if a column exists in a SQL Server table

Please see the simplest and most understandable solutions that are:

SQL Query Example 1: 

Do something, if the column does not exist:

IF COL_LENGTH('TABLE_NAME','COLUMN_NAME') IS NULL

BEGIN

     PRINT 'Column does not exist, we can add our logic here...'

END

SQL Query Example 2: 

Do something, if the column does exist:

IF COL_LENGTH('TABLE_NAME','COLUMN_NAME') IS NOT NULL

BEGIN

     PRINT 'Column Is Exists, we can add our logic here...'

END

COL_LENGTH: This function returns the defined length of a column, in bytes.

Syntax: COL_LENGTH('TABLE_NAME','COLUMN_NAME')    

Arguments:

'TABLE_NAME': The name of the table whose column length information we want to determine. table_name is an expression of type nvarchar.

'COLUMN_NAME': The column name whose length we want to determine. column_name is an expression of type nvarchar.

Note: If varchar columns are declared with the max specifier (varchar(max)), COL_LENGTH returns the value -1.