Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: November 6, 2024
Columns are one of the two main building blocks of tables. Generally, checking for a column’s existence within a table is a common practice in database management. This process enables users to perform conditional updates, avoid runtime errors in SQL scripts, and ensure integrity.
Moreover, each major database management system (DBMS) offers unique column check methods. This includes using a combination of queries and system information views.
In this tutorial, we’ll see how to check whether a column exists in a table.
Specifically, we’ll focus on three DBMSs with practical examples:
To that end, we’ll use our Simple University Schema.
There are multiple cases where checking a column’s existence may be useful:
Further, we see instructions and code examples for MSSQL, MySQL, and PostgreSQL.
The information schema enables users to work with database metadata in MSSQL. To support this, the DBMS stores the database structure and many other aspects of the database information:
The sqlcmd utility enables users to employ Transact-SQL statements in different ways:
Knowing this, we can move on to checking for column existence.
In MSSQL, checking for column existence is commonly achieved using the INFORMATION SCHEMA – COLUMNS view.
Let’s create an .sql file to setup the query:
$ cat CoulmnTest.sql
Use University;
if exists (select
*
from
INFORMATION_SCHEMA.columns
where
table_name = 'Course'
and column_name = 'textbook'
)
PRINT 'Column exists';
ELSE
PRINT 'Column does not exist';
GO
In the above example, the IF EXISTS statement examines the COLUMNS view. For example, if there is a column FirstName, it prints Column exists. Otherwise, it prints Column does not exist.
Let’s run the file from the system terminal:
$ sudo sqlcmd -S localhost -U sa -P '<ENTER_PASSWORD>' -No -i ColumnTest.sql
Changed database...
Column exists
In the above command, sqlcmd employs several options:
The above code checks the column length of the given table name. However, this approach works if the user has permission to view the object. As a result, if the column length is NULL, we get the message Column does not exist. Otherwise, we see Column exists.
We can also try changing the column name to check whether the ELSE statement works as intended. This method is reliable for conditional scripting in MSSQL.
Alternatively, we can also use the COL_LENGTH function.
Let’s make a small change to the .sql file:
$ cat ColumnTest2.sql
Use University;
IF COL_LENGTH('Course','book') IS NULL
BEGIN
PRINT 'Column does not exist';
END
ELSE
BEGIN
PRINT 'Column exists';
END
GO
Here, COL_LENGTH provides the length of a column.
Consequently, we get the same result on running the code:
$ sudo sqlcmd -S localhost -U sa -P '<ENTER_PASSWORD>' -No -i ColumnTest.sql
Changed database context ...
Column does not exist
In the same way, we can check the case of the MySQL database.
Similar to MSSQL, in MySQL, column existence checks are often performed using the INFORMATION SCHEMA database. As a matter of fact, this database stores metadata about all tables and columns within all the databases.
In this case, we use the COLUMNS table that contains data about columns in tables.
To start with, we log in to the MySQL server:
$ sudo mysql -u root -p
Let’s write a query to check whether a specified column exists in the Course table:
mysql> SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'University' AND table_name = 'Course' AND column_name = 'name';
+----------+
| COUNT(*) |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
Further, we break down the components in the above example:
As a result, if the output is greater than zero, the column exists. Otherwise, it doesn’t.
In PostgreSQL, checking for a column’s existence can be done using the INFORMATION SCHEMA COLUMNS table. In essence, it contains metadata about all columns in the database.
Same as before, we connect to the PostgreSQL server with the default user postgres:
$ sudo --login --user=postgres
Then, in the new prompt, we run psql:
postgres@ubuntu:~$ psql
psql (14.13 (Ubuntu ...)
Type "help" for help.
postgres=#
Likewise, we connect to the database:
postgres=# \c university
You are now connected to database ...
sampledb=#
Finally, we’re logged into university.
Essentially, a fairly basic PostgreSQL query checks for the existence of a column:
university=# SELECT column_name FROM information_schema.columns WHERE table_name = 'course' AND column_name = 'textbook';
column_name
-------------
textbook
(1 row)
As a result, if the column exists, the query returns the column name. Otherwise, we get no results.
In this article, we saw how to check whether a column exists within a table. Overall, we worked with three different DBMSs:
Each system has unique methods for performing the checks. Generally, these methods make use of metadata queries. Such checks help ensure database scripts run smoothly. As a result, we can prevent unexpected errors, and enable conditional updates based on schema configurations.