Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Check If Field Exists and Return Result Set in MySQL



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)
Updated on: 2019-07-30T22:30:25+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements