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

Sql ServerSql Server-2008TsqlSql Server-2012Sql Server-2016

Sql Server Problem Overview


I need to add a specific column if it does not exist. I have something like the following, but it always returns false:

IF EXISTS(SELECT *
		  FROM   INFORMATION_SCHEMA.COLUMNS
		  WHERE  TABLE_NAME = 'myTableName'
				 AND COLUMN_NAME = 'myColumnName') 

How can I check if a column exists in a table of the SQL Server database?

Sql Server Solutions


Solution 1 - Sql Server

SQL Server 2005 onwards:

IF EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'columnName'
          AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
    -- Column Exists
END

Martin Smith's version is shorter:

IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END

Solution 2 - Sql Server

A more concise version

IF COL_LENGTH('table_name','column_name') IS NULL
BEGIN
/* Column does not exist or caller does not have permission to view the object */
END

The point about permissions on viewing metadata applies to all answers, not just this one.

Note that the first parameter table name to COL_LENGTH can be in one, two, or three part name format as required.

An example referencing a table in a different database is:

COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')

One difference with this answer, compared to using the metadata views, is that metadata functions, such as COL_LENGTH, always only return data about committed changes, irrespective of the isolation level in effect.

Solution 3 - Sql Server

Tweak the below to suit your specific requirements:

if not exists (select
                     column_name
               from
                     INFORMATION_SCHEMA.columns
               where
                     table_name = 'MyTable'
                     and column_name = 'MyColumn')
    alter table MyTable add MyColumn int

That should work - take a careful look over your code for stupid mistakes; are you querying INFORMATION_SCHEMA on the same database as your insert is being applied to for example? Do you have a typo in your table/column name in either statement?

Solution 4 - Sql Server

Try this...

IF NOT EXISTS(
  SELECT TOP 1 1
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE 
    [TABLE_NAME] = 'Employees'
    AND [COLUMN_NAME] = 'EmployeeID')
BEGIN
  ALTER TABLE [Employees]
    ADD [EmployeeID] INT NULL
END

Solution 5 - Sql Server

For the people who are checking the column existence before dropping it.

From SQL Server 2016 you can use new DIE (Drop If Exists) statements instead of big IF wrappers

ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name

Solution 6 - Sql Server

I'd prefer INFORMATION_SCHEMA.COLUMNS over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, dbo.syscolumns does still work in SQL Server 2008, but it's deprecated and could be removed at any time in future.

Solution 7 - Sql Server

You can use the information schema system views to find out pretty much anything about the tables you're interested in:

SELECT *
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_NAME = 'yourTableName'
 ORDER BY ORDINAL_POSITION

You can also interrogate views, stored procedures and pretty much anything about the database using the Information_schema views.

Solution 8 - Sql Server

Try something like:

CREATE FUNCTION ColumnExists(@TableName varchar(100), @ColumnName varchar(100))
RETURNS varchar(1) AS
BEGIN
DECLARE @Result varchar(1);
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName)
BEGIN
    SET @Result = 'T'
END
ELSE
BEGIN
    SET @Result = 'F'
END
RETURN @Result;
END
GO

GRANT EXECUTE ON  [ColumnExists] TO [whoever]
GO

Then use it like this:

IF ColumnExists('xxx', 'yyyy') = 'F'
BEGIN
  ALTER TABLE xxx
  ADD yyyyy varChar(10) NOT NULL
END
GO

It should work on both SQL Server 2000 and SQL Server 2005. I am not sure about SQL Server 2008, but I don't see why not.

Solution 9 - Sql Server

First check if the table/column(id/name) combination exists in dbo.syscolumns (an internal SQL Server table that contains field definitions), and if not issue the appropriate ALTER TABLE query to add it. For example:

IF NOT EXISTS ( SELECT  *
            FROM    syscolumns
            WHERE   id = OBJECT_ID('Client')
                    AND name = 'Name' ) 
ALTER TABLE Client
ADD Name VARCHAR(64) NULL

Solution 10 - Sql Server

A good friend and colleague of mine showed me how you can also use an IF block with SQL functions OBJECT_ID and COLUMNPROPERTY in SQL Server 2005 and later to check for a column. You can use something similar to the following:

You can see for yourself here:

IF (OBJECT_ID(N'[dbo].[myTable]') IS NOT NULL AND
    COLUMNPROPERTY( OBJECT_ID(N'[dbo].[myTable]'), 'ThisColumnDoesNotExist', 'ColumnId') IS NULL)
BEGIN
    SELECT 'Column does not exist -- You can add TSQL to add the column here'
END

Solution 11 - Sql Server

declare @myColumn   as nvarchar(128)
set @myColumn = 'myColumn'
if not exists (
    select  1
    from    information_schema.columns columns 
    where   columns.table_catalog   = 'myDatabase'
        and columns.table_schema    = 'mySchema' 
        and columns.table_name      = 'myTable' 
        and columns.column_name     = @myColumn
    )
begin
    exec('alter table myDatabase.mySchema.myTable add'
    +'    ['+@myColumn+'] bigint       null')
end

Solution 12 - Sql Server

This worked for me in SQL Server 2000:

IF EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE table_name = 'table_name'
    AND column_name = 'column_name'
)
BEGIN
...
END

Solution 13 - Sql Server

Try this

SELECT COLUMNS.*
FROM   INFORMATION_SCHEMA.COLUMNS COLUMNS,
	   INFORMATION_SCHEMA.TABLES TABLES
WHERE  COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
	   AND Upper(COLUMNS.COLUMN_NAME) = Upper('column_name') 

Solution 14 - Sql Server

I needed something similar for SQL Server 2000 and, as Mitch points out, this only works in SQL Server 2005 or later.

This is what worked for me in the end:

if exists (
    select *
    from
        sysobjects, syscolumns
    where
        sysobjects.id = syscolumns.id
        and sysobjects.name = 'table'
        and syscolumns.name = 'column')

Solution 15 - Sql Server

IF NOT EXISTS(SELECT NULL
              FROM  INFORMATION_SCHEMA.COLUMNS
              WHERE table_name = 'TableName'
                    AND table_schema = 'SchemaName'
                    AND column_name = 'ColumnName') BEGIN

  ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';

END;

Solution 16 - Sql Server

if exists (
  select * 
  from INFORMATION_SCHEMA.COLUMNS 
  where TABLE_NAME = '<table_name>' 
  and COLUMN_NAME = '<column_name>'
) begin
  print 'Column you have specified exists'
end else begin
  print 'Column does not exist'
end

Solution 17 - Sql Server

A temporary table version of the accepted answer:

if (exists(select 1
           from tempdb.sys.columns
           where Name = 'columnName'
                 and Object_ID = object_id('tempdb..#tableName')))
begin
...
end

Solution 18 - Sql Server

One of the simplest and understandable solutions is:

IF COL_LENGTH('Table_Name','Column_Name') IS NULL
  BEGIN
    -- Column Not Exists, implement your logic
  END
ELSE
  BEGIN
    -- Column Exists, implement your logic
  END

Solution 19 - Sql Server

select distinct object_name(sc.id)
from syscolumns sc,sysobjects so  
where sc.name like '%col_name%' and so.type='U'

Solution 20 - Sql Server

Wheat's answer is good, but it assumes you do not have any identical table name / column name pairs in any schema or database. To make it safe for that condition, use this...

select *
from Information_Schema.Columns
where Table_Catalog = 'DatabaseName'
  and Table_Schema = 'SchemaName'
  and Table_Name = 'TableName'
  and Column_Name = 'ColumnName'

Solution 21 - Sql Server

There are several ways to check the existence of a column. I would strongly recommend to use INFORMATION_SCHEMA.COLUMNS as it is created in order to communicate with user. Consider following tables:

 sys.objects
 sys.columns

and even some other access methods available to check system catalog.

Also, no need to use SELECT *, simply test it by NULL value

IF EXISTS(
           SELECT NULL 
           FROM INFORMATION_SCHEMA.COLUMNS
           WHERE
             TABLE_NAME = 'myTableName'
             AND COLUMN_NAME = 'myColumnName'
         ) 

Solution 22 - Sql Server

Do something if the column does not exist:

BEGIN
    IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NULL)
    BEGIN
        // Do something
    END
END;

Do something if the column does exist:

BEGIN
    IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NOT NULL)
    BEGIN
        // Do something
    END
END;

Solution 23 - Sql Server

Here is a simple script I use to manage addition of columns in the database:

IF NOT EXISTS (
		SELECT *
		FROM sys.Columns
		WHERE Name = N'QbId'
			AND Object_Id = Object_Id(N'Driver')
		)
BEGIN
	ALTER TABLE Driver ADD QbId NVARCHAR(20) NULL
END
ELSE
BEGIN
	PRINT 'QbId is already added on Driver'
END

In this example, the Name is the ColumnName to be added and Object_Id is the TableName

Solution 24 - Sql Server

Another contribution is the following sample that adds the column if it does not exist.

    USE [Northwind]
    GO

    IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE TABLE_NAME = 'Categories'
                        AND COLUMN_NAME = 'Note')
    BEGIN

    ALTER TABLE Categories ADD Note NVARCHAR(800) NULL

    END
    GO

Solution 25 - Sql Server

The below query can be used to check whether searched column exists or not in the table. We can take a decision based on the searched result, also as shown below.

IF EXISTS (SELECT 'Y' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = <YourTableName> AND COLUMN_NAME = <YourColumnName>)
  BEGIN
    SELECT 'Column Already Exists.'
  END
  ELSE
  BEGIN
    ALTER TABLE <YourTableName> ADD <YourColumnName> <DataType>[Size]
  END

Solution 26 - Sql Server

Yet another variation...

SELECT 
  Count(*) AS existFlag 
FROM 
  sys.columns 
WHERE 
  [name] = N 'ColumnName' 
  AND [object_id] = OBJECT_ID(N 'TableName')

Solution 27 - Sql Server

You can check multiple columns in SQLDB at once and return a string as status to check if columns exist:

IF EXISTS
        (
          SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = 'Table Name'
          AND(COLUMN_NAME = 'column 1'
          or COLUMN_NAME = 'column 2'
          or COLUMN_NAME = 'column 3'
          or COLUMN_NAME = 'column 4')
        )
        SELECT 'Column exists in table' AS[Status];
        ELSE
        SELECT 'Column does not exist in table' AS[Status];

Solution 28 - Sql Server

Execute the below query to check if the column exists in the given table:

IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';

Solution 29 - Sql Server

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database Name'
and TABLE_SCHEMA = 'Schema Name'
and TABLE_NAME = 'Table Name'
and COLUMN_NAME = 'Column Name'
and DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.

BEGIN
  -- Column exists in table
END

ELSE BEGIN
  -- Column does not exist in table
END

Solution 30 - Sql Server

IF EXISTS(SELECT 1 FROM sys.columns
      WHERE Name = N'columnName'
      AND Object_ID = Object_ID(N'schemaName.tableName'))

This should be the fairly easier way and straightforward solution to this problem. I have used this multiple times for similar scenarios. It works like a charm, no doubts on that.

Solution 31 - Sql Server

Table → script table as → new windows - you have design script.

Check and find the column name in the new windows.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaciejView Question on Stackoverflow
Solution 1 - Sql ServerMitch WheatView Answer on Stackoverflow
Solution 2 - Sql ServerMartin SmithView Answer on Stackoverflow
Solution 3 - Sql ServerLuke BennettView Answer on Stackoverflow
Solution 4 - Sql ServerLeon TaysonView Answer on Stackoverflow
Solution 5 - Sql ServerPரதீப்View Answer on Stackoverflow
Solution 6 - Sql ServerChristian HayterView Answer on Stackoverflow
Solution 7 - Sql ServeranonymousView Answer on Stackoverflow
Solution 8 - Sql ServerMatt LaceyView Answer on Stackoverflow
Solution 9 - Sql ServermdbView Answer on Stackoverflow
Solution 10 - Sql ServerbrazilianldsjaguarView Answer on Stackoverflow
Solution 11 - Sql ServerTuomo KämäräinenView Answer on Stackoverflow
Solution 12 - Sql ServerJoe MView Answer on Stackoverflow
Solution 13 - Sql ServerDouglas TondoView Answer on Stackoverflow
Solution 14 - Sql ServerFrostbiteXIIIView Answer on Stackoverflow
Solution 15 - Sql ServerNa30mView Answer on Stackoverflow
Solution 16 - Sql ServerBYRAKUR SURESH BABUView Answer on Stackoverflow
Solution 17 - Sql ServercrokusekView Answer on Stackoverflow
Solution 18 - Sql ServerArsman AhmadView Answer on Stackoverflow
Solution 19 - Sql ServerNishadView Answer on Stackoverflow
Solution 20 - Sql ServerDaniel BarbalaceView Answer on Stackoverflow
Solution 21 - Sql ServerAli ElmiView Answer on Stackoverflow
Solution 22 - Sql ServerJagjit SinghView Answer on Stackoverflow
Solution 23 - Sql ServerUJSView Answer on Stackoverflow
Solution 24 - Sql ServerSimone SpagnaView Answer on Stackoverflow
Solution 25 - Sql ServerSuraj KumarView Answer on Stackoverflow
Solution 26 - Sql ServerManuel AlvesView Answer on Stackoverflow
Solution 27 - Sql ServerMostafa BouzariView Answer on Stackoverflow
Solution 28 - Sql ServerS KrishnaView Answer on Stackoverflow
Solution 29 - Sql ServerMohammad Reza ShahrestaniView Answer on Stackoverflow
Solution 30 - Sql ServerIlangeeranView Answer on Stackoverflow
Solution 31 - Sql ServerVisheView Answer on Stackoverflow