Recently, my team was tasked with implementing a new feature in one of our products that requires adding a new column to an existing table in our SQL database. As a research, we have identified a few best approaches to do this. In this article, we will discuss 3 simple approaches to checking whether a column exists in a table in the SQL server.
To check if a column exists in the SQL Server database, use COL_LENGTH (), sys.columns, and INFORMATION_SCHEMA.COLUMNS.
I have a table named Vehicle with 4 columns: VehicleID, VehicleName, VehicleBrand, and VehicleType.
Approach-1: Using COL_LENGTH ()
We can execute the below SQL query with the COL_LENGTH ().
IF COL_LENGTH('dbo.Vehicle', 'VehicleName') IS NOT NULL
PRINT 'Column Name Exists'
ELSE
PRINT 'Column Name doesn't Exist'
After executing the above query, which checks whether the column name VehicleName inside the Vehicle table exists, I got the expected output as “Column Name Exists.” Check out the screenshot below for your reference.
Check out How to change column name in SQL Server
Approach-2: Using sys.columns
We can also execute the SQL query with the sys.columns.
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'VehicleName'
AND Object_ID = Object_ID(N'dbo.Vehicle'))
PRINT 'Column Name Exists'
ELSE
PRINT 'Column Name doesn''t Exists'
After executing the above query, I got the expected output below.
Check out How to check if table exists in SQL Server
Approach-3: Using INFORMATION_SCHEMA.COLUMNS
We can also execute the SQL query with the INFORMATION_SCHEMA.COLUMNS for this purpose.
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Vehicle'
AND column_name = 'Name'
)
PRINT 'Column Name Exists'
ELSE
PRINT 'Column Name doesn''t Exists'
After executing the above column, I got the expected output as shown in the screenshot below.
Conclusion
You can use SQL queries using COL_LENGTH (), sys.columns, and INFORMATION_SCHEMA.COLUMNS to check if a column exists in the SQL server. Use the specific method based on your convenience.
You can also like following the articles below
- How to find column name in table SQL Server
- How To Truncate Table In SQL Server
- How To Copy One Table To Another In SQL Server
Grey is a highly experienced and certified database expert with over 15 years of hands-on experience in designing, implementing, and managing complex database systems. Currently employed at WEX, USA, Grey has established a reputation as a go-to resource for all things related to database management, particularly in Microsoft SQL Server and Oracle environments. He is a Certified Microsoft SQL Server Professional (MCSE: Data Management and Analytics) and Oracle Certified Professional (OCP), with Extensive database performance tuning and optimization knowledge and a proven track record in designing and implementing high-availability database solutions.