272

I want to write a query for MS SQL Server that adds a column into a table. But I don't want any error display, when I run/execute the following query.

I am using this sort of query to add a table ...

IF EXISTS (
       SELECT *
       FROM   sys.objects
       WHERE  OBJECT_ID = OBJECT_ID(N'[dbo].[Person]')
              AND TYPE IN (N'U')
   )

But I don't know how to write this query for a column.

5
  • 1
    possible duplicate of How to check if column exists in SQL Server table Jan 15, 2012 at 15:23
  • You should use sys.tables instead of the "generic" sys.objects - then you don't have to specify the type explicitly (it's obvious from the sys.tables already....)
    – marc_s
    Jan 15, 2012 at 15:44
  • COL_LENGTH Alternative only works from SQL-Server 2008, but it works.
    – Paul-Henri
    Dec 13, 2016 at 9:20
  • @MartinSmith very much NOT a duplicate of that. Your link is one possible way to solve it (and indeed, is the recommended way, right now). But the question is actually different and other solutions could be available (e.g. if SQL adds an IF NOT EXISTS clause to the ADD COLUMN syntax)
    – Brondahl
    Sep 1, 2020 at 14:53
  • @Brondahl - as the question has survived open in the 8.5 years since the comment you are replying to was posted probably no need to panic. At the moment all the answers here are basically dupes of the ones in the linked Q though Sep 1, 2020 at 15:27

7 Answers 7

306

You can use a similar construct by using the sys.columns table io sys.objects.

IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[Person]') 
         AND name = 'ColumnName'
)
8
  • 49
    Note that in this instance you want to use IF NOT EXISTS in your actual code.
    – Nat
    Apr 4, 2013 at 2:27
  • 4
    For optimized query you can use top 1 with select statement Apr 1, 2014 at 16:53
  • 29
    @BanketeshvarNarayan this is incorrect. The execution plans for subqueries in an EXISTS clause are identical. Things like SELECT 1 or SELECT TOP 1 are unnecessary. The EXISTS clause itself tells the query optimizer to only perform the minimum reads necessary to evaluate the EXISTS... at least in SQL Server. Other DB engines may have a more or less efficient query optimizer. Jul 21, 2015 at 16:56
  • 23
    @BanketeshvarNarayan If you are optimizing your ADD Column queries... you must be running them too often!
    – Fenton
    Apr 27, 2016 at 12:47
  • 2
    @Kush - Replace AND = 'ColumnName' with AND name in ('ColumnName1', 'ColumnName2') Sep 20, 2018 at 6:18
148
IF COL_LENGTH('table_name', 'column_name') IS NULL
BEGIN
    ALTER TABLE table_name
    ADD [column_name] INT
END
4
  • 1
    I tried doing this one but it returns an error which states that COL_LENGTH function does not exist. Nov 9, 2015 at 5:35
  • 6
    Requires SQL Server 2008+ Dec 16, 2016 at 6:11
  • 12
    Small addition - one shouldn't use square brackets in the column name, since COL_LENGTH('table_name', '[column_name]') always return null in SQL Server 2016 (COL_LENGTH('[table_name]', 'column_name') works as expected).
    – stop-cran
    Sep 27, 2017 at 11:05
  • that's because you are essentially quoting the string twice if you put brackets inside single quotes.
    – John Lord
    Dec 10, 2021 at 19:49
45

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null
3
  • 2
    I like it. I think the best part about posting here is finding gems like this.
    – JStead
    Jan 15, 2012 at 15:44
  • 7
    What is 'ColumnId'? Dec 20, 2019 at 7:46
  • 'ColumnId' is the name of the column property you are checking against. You could have probably used any property name that exists on a column, such as name, etc. Feb 2, 2020 at 16:17
8

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

1
  • 3
    If you're going to edit just edit it to use SYS.COLUMNS not a note to say change the query! Jul 8, 2021 at 9:23
7
IF NOT EXISTS (SELECT * FROM syscolumns
  WHERE ID=OBJECT_ID('[db].[Employee]') AND NAME='EmpName')
  ALTER TABLE [db].[Employee]
  ADD [EmpName] VARCHAR(10)
GO

I Hope this would help. More info

1
2
IF NOT EXISTS (SELECT 1  FROM SYS.COLUMNS WHERE  
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END
2

When checking for a column in another database, you can simply include the database name:

IF NOT EXISTS (
  SELECT * 
  FROM   DatabaseName.sys.columns 
  WHERE  object_id = OBJECT_ID(N'[DatabaseName].[dbo].[TableName]') 
         AND name = 'ColumnName'
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.