Write a MySQL query to check if field exists and then return the result set?

MySQLMySQLi Database

To check if field exists and then to return the result set, you can use the below syntax −

show columns from yourTableName where field='yourColumnName';

Let us first create a table −

mysql> create table DemoTable
(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserFirstName varchar(20),
   UserLastName varchar(20),
   UserAge int,
   UserAddress varchar(200),
   UserCountryName varchar(20)
);
Query OK, 0 rows affected (0.67 sec)

Here is the query to check if field exists and then return the result set −

mysql> show columns from DemoTable where field='UserCountryName';

This will produce the following output −

+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| UserCountryName | varchar(20) | YES  |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+
1 row in set (0.01 sec)

Here is the case when the column does not exist −

mysql>show columns from DemoTable where field='Marks';

This will produce the following output −

Empty set (0.00 sec)
raja
Published on 30-Apr-2019 10:43:33
Advertisements