0

I want to add a column which will be added in table only if column with same name is not exists.
Alter Table tablename add col varchar(250)

Sonam Mohite
  • 885
  • 4
  • 19
  • 51

2 Answers2

1

I think you cant just execute your SQL and retrieve the error if the column already exists.

On the other hand, if you don't want to reach a possible error situation at the MySQL side you could try something like (dynamic SQL):

SET @query = (SELECT
    IF((SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=database() AND      
     TABLE_NAME = 'YOUR_TABLE' AND COLUMN_NAME = 'COL')=0,
     CONCAT('ALTER TABLE YOUR_TABLE ADD COLUMN COL varchar(255)'),
 'SELECT ''ALREADY EXISTS'''
 ));
PREPARE st FROM @query;
EXECUTE st;

First, you will generate a SQL containing the column addition SQL or a dummy SQL depending on whether you already have the target column at the INFORMATION_SCHEMA.

PREPARE

and

EXECUTE 

statements are used to execute that query.

0

use INFORMATION_SCHEMA database

SELECT 
count(*) 
FROM
information_schema.COLUMNS
WHERE
information_schema.TABLE_SCHEMA=DB name
AND information_schema.TABLE_NAME=table name
AND information_schema.COLUMN_NAME=col name

if count is more than 0 create the column else don't

avisheks
  • 1,178
  • 10
  • 27